Notes of Visual basic

Visual Basic Programming

What is Program?

Computer is a machine so computer, do nothing its self we must give some instruction to perform any task. The set of instruction that is given to computer to solve any problem is called program.

What is Language?

When we have to solve any problem then we write computer program in which we give some instruction to computer. These instructions are written in some special computer language. These languages are divided in to three general types.
1 Machine language
2 Assembly Language
3 High Level Language
Any computer directly understands only its own machine language. Machine language is natural language of computer. Machine language composed on binary code (0 and 1). Machine language is machine dependent language. It means that particular machine language only run on one type of computer.
It is difficult to understand the machine language so with passing of time and development assembly language was introduced which consist on some abbreviations of machine code. User directly writes these abbreviations, a translator program converts these assembly codes in to machine codes. This translator, which translates the assembly codes in to machine codes, is called ASSEMBLER.
The modern computer languages are High-level languages. In these types of languages we write instruction in simple English language. We also use simple mathematical notation like that mathematical operators and expressions. A translator program converts the program written in high level language into machine code is called compiler and interpreter.

What is Visual Basic? And some important Feature of Visual Basic?

Visual Basis is Microsoft windows programming language. Visual Basic programming created in integrated development editor (IDE). This IDE allow to programmer that create, Run and Debug the program in fraction of time. The process of rapidly creating an application is called Rapid Application Development (RAD). Visual Basic provides many advanced features of programming. It provide the facility that user can create GUI (Graphical User Interface Environments). It also provides some object oriented programming feature, and structure programming features. Visual basic have event driven programming feature which provide facility that user can execute any procedure any time by clicking mouse or performing any action. Visual Basic provide facility that user can access WIN32 API (Application Programming Interface). Which make VB as Multithreading programming. (its means user can access directly windows components by which user can perform Multi task which is not possible in any other high level language like that JAVA). In Visual Basic there is no need of writing the Codes of creating user interface like that design the Form, Text Box, Message Box and Command button. User can include all these user interface object just deranging or clicking which safe the time and energy.

Data Type In VB

The values, which we use in coding or programming, are referred to a data.
The data type of a programming element refers to what kind of data it can hold and how it stores that data. Data types apply to all values that can be stored in computer memory or participate in the evaluation of an expression. Every variable, literal, constant, property, procedure parameter, procedure argument, and procedure return value has a data type.
Visual Basic supplies a set of predefined data types, which you can use for many of your programming elements.
In Visual Basic 6 there are 11 different data types these data type or mainly divide in to three categories
1. Numeric Data Type
2. Character Data Type
3. Special Data Type (Miscellaneous Data Types)
4. Composite Data Types

1) Numeric Data Type: -

This type of data consist on numbers such as 233,-23,2.3etc.This type of data further divide in to following types.
Integral Numeric Types
Integral data types are those that represent only numbers without fractional parts.
a) Integer Data Type: -
This type of data used to store the whole number like that 500, 340.This type of data take 2 bytes and maximum range of this type of data is -32768 to 32767.
b) Longer Integer: -
The Long data type is a 32-bit number, which can range from -2,147,483,648 to 2,147,483,647. Long variables can only contain non-fractional integer values. I myself use Long variables over Integers for increased performance. Most Win32 functions use this data type for this reason.
c) Byte: -
The Byte data type is an 8-bit variable, which can store value from 0 to 255. This data type is very useful for storing binary data. It can also be very useful when sending/receiving byte values to/from a Basic Stamp or PIC.
No integral Numeric Types
a) Single Data Type: -
The Single data type is a 32-bit number ranging from 3.402823e38 to -1.401298e-45 for negative values and from 1.401298e-45 to 3.402823e38 for positive values. When you need fractional numbers within this range, this is the data type to use.
b) Double Data Type: -
The Double data type is a 64-bit floating-point number used when high accuracy is needed. These variables can range from1.79769313486232e308 to -4.94065645841247e-324 for negative values and from 4.94065645841247e-324 to 1.79769313486232e308 for positive values.

2) Character Data Type

This type related with string value. When we want to give the data in shape have alphabetic or Text then we use Character data type. It is further divide in to following types.
Char Data type: -
The Char data type is a single two-byte (16-bit) Unicode character. If a variable always stores exactly one character, declare it as Char.
String Data Type
The String data type is a sequence of zero or more two-byte (16-bit) Unicode characters. If a variable can contain an indefinite number of characters, declare it as String. Following are the some String Data Type.
a) String Variable Length: -
It takes 10 bytes of memory plus string length. In this type of data we can store more then 2 billion character.
b) String Fix Length: -
It takes bytes of memory equal to the string length. If we enter string "shah” then it takes 4 bytes of memory.
3) Special Data Type (Miscellaneous Data Types)
Visual Basic supplies several data types that are not oriented toward numbers or characters. Instead, they deal with specialized data such as yes/no values, date/time values, and object addresses. Some special data type are given below:
a) Boolean Type: -
The Boolean Data Type (Visual Basic) is an unsigned value that is interpreted as either True or False. Its data width depends on the implementing platform. If a variable can contain only two-state values such as true/false, yes/no, or on/off, declare it as Boolean.
b) Date Type: -
The Date Data Type (Visual Basic) is a 64-bit value that holds both date and time information. Each increment represents 100 nanoseconds of elapsed time since the beginning (12:00 AM) of January 1 of the year 1 in the Gregorian calendar. If a variable can contain a date value, a time value, or both, declare it as Date.
d) Object Type: -
The Object Data Type is a 32-bit address that points to an object instance within your application or in some other application. An Object variable can refer to any object your application recognizes, or to data of any data type. If a variable stores a pointer to an instance of a class that you do not know at compile time, or if it can point to data of various data types, declare it as Object.
2) Composite Data Types
In addition to the elementary data types Visual Basic supplies, you can also assemble items of different types to create composite data types such as structures, arrays, and classes. You can build composite data types from elementary types and from other composite types. For example, you can define an array of structure elements, or a structure with array members.

Variable In VB

Values that changed during the execution of program are called variable. We say that variable hold constant value. In programming terminology we say that variable are those memory location, which hold the constant values. Variable type depend on the data which variable store.
For example if we store integer data like that 300 in variable n than n is integer variable. In other word we say that variable may be numeric value, string value etc.
So according to above definition Variable is use for storing the value in computer memory.
Variable have name, which is referring to memory location, and this name remain same but value at this location will be change.
Rules For Naming The variable 1) The first character of variable name must be alphabetic.
2) Blank Space is not allowed in variable name.
3) The name may be in upper case are lower case.
4) Reserved word is not allowed as variable name.
5) Maximum length of variable name is 255 characters.

Types of Variable: -

In visual basic type of variable depend on the data type, which hold by the variable. Following are the some type of variable which are used in visual basic.
1 Boolean Variable
2 Char Variable
3 Byte Variables
4 Date Variables
5 Decimal Variables
6 Double Variables
7 Integer Variables
8 Object Variables
9 Long Variables
10 Short Variables
11 String Variables
1) Boolean Variable: -
The Visual Basic Boolean variable type holds a value of true or false. Internally these are actually stored as the numbers 1 and 0 representing true and false respectively. Boolean values are used in conditional statements to decide whether particular parts of Visual Basic code should be executed or not (see Visual Basic Flow Control for more details on conditional statements).
2) Char Variable: -
The Char variable type holds a single character (such as the letter 'B'). The value of a Char can be any character. Internally, a number in the range 0 to 65,553 is used to represent the character value as defined by the ASCII table. As an example when the letter 'Z' is assigned to a Visual Basic Char variable, the number 90 is actually stored in the variable location.
3) Byte Variable: -
A Byte variable holds a positive number in the range 0 to 255. Because of the limited range, Byte variables should be used with caution. An attempt to assign a negative value or a value greater than 255 to a Visual Basic Byte variable will result in an error.
4) Date Variable: -
The Visual Basic Date variable type holds a date and time value. Dates are declared in the form #mm/dd/yyyy#. For example, May 23, 2007 would be declared as #5/23/2007#. Visual Basic provides a number of mechanisms for working with Date variables (such as calculating a date six months from today's date). These are covered in the Working with Dates and Times in Visual Basic section of this book.
5) Decimal Variable: -
The Decimal variable type can store either a whole number or a decimal number up to 29 decimal places. When working with whole numbers, however, it is recommended that the Integer variable type be used as this is more memory efficient than the Decimal variable type.
6) Double Variable: -
The Visual Basic Double variable is used to store either very large numbers, or small numbers requiring more than 28 decimal places. To be precise Visual basic Double variables can store positive numbers in the range 4.94065645841246544E-324 to 1.79769313486231570E+308 and negative numbers from -1.79769313486231570E+30 to -4.94065645841246544E-324.
Double variables are typically used when developing scientific applications using Visual Basic and, as such, are generally not used by the average developer.
7) Integer Variable: - The Visual Basic Integer variable type is used to store whole numbers between -2,147,483,648 and 2,147,483,648. The Integer variable cannot be used to store numbers containing decimals.
8) Object Variable: -
The Object variable is a catch-all variable type which can be used to store a value of any data type. Because of this flexibility, an Object variable will typically reserve more memory than is needed for most variable types. For this reason, it is more efficient to use the correct variable type for the value you need to store (such as Char for a character or Integer for a whole number) rather than use the Object variable type.
9) Long Variable: -
The Visual Basic Long variable type is used to store whole numbers ranging from -9,233,372,036,854,775,808 to 9,233,372,036,854,775,807.
10) Short Variable: -
A Short variable in Visual Basic stores a whole number in the range -32,768 to 32,767.
11) String Variable: -
The String variable type stores multiple characters that make up words or sentences. String variables are encapsulated in double-quotation marks ("). For example "Hello" is a string, as is "Hello, this is a test".

Two Way Variable: -
These are the variable, which perform two functions sending the data to sub procedure and receive the data form sub procedure.

Declaration of Variable

When we specify the variable name and variable type then it is called Declaration of variable. When we declare a variable then certain number of bytes in the memory is allocated which depend on the data type.
There are three type of declaration are used in VB.
1) Implicit Declaration
2) Explicit Declaration
3) Default Declaration
1. Implicit Deceleration: -
When we declare a variable during the execution of program at that time when value is assigned. It is called implicit declaration.
In this type when data is assigned to variable then visual basic first declare a variable at run time and then give the value to it.
When the Variable is declare then character suffix is used for this purpose.
Syntax is.
Variable name {Suffix} = data
Where suffix is used for variable type.

 Suffix character		Data Type
	$			String
	%			Integer
	&			Long
	!			Single
	#			Double
Example	n$=100 	(Show n is integer variable which hold value 100).

2. Explicit Declaration: -
When we declare a variable before assigning the value is called explicit declaration. Explicit variable declaration depends on the scope of variable.
For declaration of explicit variable we used a reserve word Dim, Static or global.
Syntax: -
Dim Variable-Name As data-type
For example
Dim n As Integer
We also use suffix at the place of key word As with Data type.
Dim n $
Where $ show that n is integer variable.
3. Default Declaration: -
If a variable is not declared as implicit or explicit then it declared by default and called variant type of variable. A variant type of variable can hold any type of data value and it is declared during execution of program when a value is assigned to it.
If require variable declaration option is selected then the variant type of variable must be declared explicitly. In this case declare statement used Dim, Static type of reserve word with out specifying the data type.
Requiring variable option: -
In Visual Basic we assigned the data to variable with out t declaring a variable. For this purpose we change the setting form declaration option form edit menu.
Select the tools
Select the option
Select the require variable declaration option (Check This Option).
And following statement must be written before the procedure
Option Explicit

Scope of variable

The scope of variable specifies the range of variable in the application in which variable can be access and used.
There are four 4 level of scope in Visual Basic application.
1. Procedure Level
2. Procedure level Static
3. Form and Module Level
4. Application Level
1 Procedure Level: -
The variable which is define in any procedure is called procedure level variable. They cannot be used in any other procedure and they do not retain their value once procedure is terminates. So we can say that scope of procedure level variable is in the procedure in which this variable is define. These types of variables are called local level variables.
This type of variable are define in the procedure with dim keyword,
2. Procedure Level Static: -
These variables also define in procedure. But these are declares with Static keyword. The scope of these types of variables also with in the procedure in which this variable is defined but it retains their value once procedure id terminates.
Static S As String
3. Form And Module Level variables: -
These types of variable declared in the declaration part of Code Window (First of all before coding any code). The Scope of this type of variable is in the form or module in which it is define. The key word Dim is used for this purpose.
4. Global Level Variable: -
These types of variables are more power full from all other variable. These types of variables are accessible from any where from the application. The Global level variables are defined in the module. Keyword "Global” is used for this purpose.
Life Time of All Variables
The period for which the variables retain there value is called lifetime of variable.
Global Level Variable retains their value as well as the program is running.
Local Level Or Procedure Level is defining with keyword Dim and is retaining their value as long the procedure is running.
The local Level variable, which is defined with keyword Static, retain their value after the termination of procedure. So the lifetime of this type of variable is as well as program is running.

Constants in VB

The quantity that do not change its value during the execution of program is called constant
1.Numeric Constant: -
These are number like that 200, 600, 1.5 etc
2. String constant: -
When any value is enclosed in double courts than this value considered as string constant normally messages display with the help of string constant.
3.User-Define Constant: -
We can also assign a value to a variable in such manner that this value dos not change during the execution of program. So we can say that a variable that behave like a constant is called User Define constant.
The Key word const is use for this purpose. The user define constant are usually written in capital latter to distinguish them form variable.
For example Const X1=500
The scope of these type of constant are same as the scope of other variable like that if user define constant are define in procedure then it treated like that procedural level variable.
4.Visual basic symbolic constant: -
The visual Basic uses many values to specify the object properties. These value are numeric constant but difficult in nature. Like that color property have some value in shape of special code in hexadecimal value like that for blue color we use &hff000 and it is difficult for user that he remember that type of value.
So Visual Basic assigned some name to this type of value. These names are called VB Symbolic constant.
For example for blue color we use
Form1.backcolor= vbblue

Operator in VB

Operators are the special symbols that are used to perform the special function in Visual Basic.
The following are most commonly used operator.
1. Arithmetic Operator
2. Logical Operator
3. Assignment Operator
4. Relational operator
1. Arithmetic Operator: -
These are the operator, which perform the arithmetic function Like that Addition, Multiplication etc. Following are Arithmetic operator.

Operator 				Function 
+	For addition of number
-	For subtraction of number
/	Division of two number
^	It is used to calculate the power.
\”	It is used for integer division
Mod	For calculate the remainder.	

2. Relational Operator: -
These are the operators that are used to compare two values. The result of relational operator is always TRUE or FALSE.
Following are the relational operator.
Operator Function
> (Grater than symbol) When 1st value is grater then 2nd then it return TRUE other wise FALSE.
< (Less Then symbol) When 1st value is less then 2nd than return TRUE other wise FALSE.
>= (Grater the or equal) When 1st value is grater then or equal to 2nd value than it return TRUE other then FALSE.
<= (Less then or equal) When 1st value is less then or equal to 2nd value than it return TRUE other then FALSE.
= (Equal to symbol) When 1st value is equal to 2nd vale than it return TRUE other then FALSE.
For example if we have two variable X =20 and Y=10 and we compare then
X > Y Return TRUE and X < Y Return FALSE
3. Logical operator: -
These are the operators, which are used to combine the two relational expressions. The result of logical operator is always TRUE or FALSE.
Following are the logical operator.
a) And operator:
If expression 1 and expression 2 both true then result of AND operator return TRUE and if nay one expression is FALSE the result return FALSE.
If we have A=10, B= 5, C= 3 and D = 1 then following table show the out put of "AND "operator
Expressions Result

A > B     AND   C  >  DTRUE    AND    TRUE	 TRUE
A > B     AND   C  <  DTRUE    AND    FALSE	FALSE
A < B     AND   C  >  DFALSE   AND    TRUE	FALSE
A < B     AND    C  <  DFALSE   AND     FALSE	FALSE

Above table show that result is TRUE only in that case if both expressions return TRUE result.
b) OR Operator: -
If any expression from expression 1 and expression 2 is TRUE then result of OR operator return TRUE. This operator only returns FALSE if the result of both expressions is FALSE.
If we have A=10,B=5,C=3andD=1then following table show the out put of "OR "operator
Expressions Result

A > B    OR   C  >  DTRUE   OR    TRUE	 TRUE
A > B    OR   C  <  DTRUE   OR    FALSE	TRUE
A < B    OR   C  >  DFALSE   OR    TRUE	TRUE

Above table show that result is FALSE only in that case if both expressions return FALSE result.
c) NOT Operator: -
If the result of expression is TRUE than out put of this operator is FALSE and if the output of expression is FALSE then this operator return TRUE. In simple word it convert the result TRUE to FALSE And FALSE to TRUE.
For example if A=10 and B=5 then result of following expression is
NOT (A > B)
Xor Operator: -
If expersion1 and expression2 are differ form each other then result of Xor Operator is TRUE other wise FALSE.
Eqv Operator: -
If expersion1 and expression2 are produced same result then result of Eqv Operator is TRUE other wise FALSE

Expression in VB

An expression is a collection of operand and operator. Where operand means collection of constant and variable. In simple word we say that an expression is used for calculating the value of formula. It is combination of different operand and operator.
If we calculate the value of box with given sides size A, B, C. Then expression is
A * B * C
Where A, B ,C may be variable or constant and * (asterisk ) Arithmetic operator .
Following are three type of expression used in Visual Basic.
1) Arithmetic Expression: -
These are the combination of operand and Arithmetic operator.
For example = A + B
Where A and B are variable or constant (operand) and + sign is Arithmetic operator.
2) Relational Expression: -
Relational Expression is used to find the relation between two expressions. These expressions may be arithmetic expression, or may any operand.
For example = A > B
10 = 4
A + B = D
Where A, B and C are any variable. It returns true or false. If the expression is true then result is true other then false.
4) Logical Expression: -
A logical expression combined two relational expressions. For combining two expressions logical operators (AND, OR, NOT, Xor, Equ) are used.
For example
A > B AND C > D
It returns True or False depending on the result of tow expression.

Input Out Put Dialog Boxes in VB

In VB special types of dialog box are use to provide and get the information (Input And Out put) from user are called input out put dialog box.
There are two type of dialog box are use.
1. Message Dialog Box
2. Input Dialog Box

1. Message Box: -

The message dialog box is used to provide information to user. It is usually used as Error Message or Provide the Guidance to the user and short message is displayed in the box
[ Integre Variable ]=MsgBox ("strmsg or message”,Dlg def,Title)
Title: -
It is title of the message Box, which specifies that what type of message this box contain. This message appeared in title bar of message box.
Strmsg: -
It specifies a string constant or string variable. It is usually a massage, which is display in the message box.
Dlgdef: -
Dlgdef stand for dialog definition. It is optional argument. it is use to select the number of button and type of Icon which is displayed on the message box. For this purpose we use integer value or VbConstant. These are follows.

Vbokonly 0 Display ok button
Vbokcancel 1 Display ok and cancel button
Vbabortretryignor 2 Display abort, retry, ignore button
Vbnocancel 3 Display no and cancel button
Vb yesno 4 Vb yes and no button
Vbretrycancel 5

For display the icon we use following value and lateral (vb constant)

Vb critical 16 Critical icon display
Vb question 32 Question mark icon
Vb exclamation 48 Exclamation marks is displayed
Vb information 64 Information icon is displayed

Default button:
The button on the message box that has the control is known as the default button. A message box can have maximum three buttons and the left button is considered as a first button and so on.
If we specify which button is default then we use following lateral or value.

Vbdefaultbutton1 0 First button is default.
Vbdefaultbutton2 256 2nd button is default.
Vbdefaultbutton3 512 3rd button is default.

Mode of dialog message box: -
There are three mode of message dialog box.
1. Application specific mode: - In this mode dialog box take control of application. User must response to the dialog box before continuing working program. However user can switch over to other application. This is default setting of the message box.
2. System specific mode: - In this mode user cannot work on any application on the computer system. For this purpose we used vbsystemmodal vb constant or 4096 value in dlgdef portion of the message box.
Message box return value: - The message box is a function. It returns a value as integer when we click on the any button of the message box. Very button return different value. There are 7 type of button used in the message box so they return 7 type of value.

Vbok 1 Ok button is clicked
Vbcancel 2 Cancel button is clicked
Vbabort 3 Abort is clicked


Retry button is clicked
Vbignore 5 Ignore button is clicked.
Vbyes 6 Yes button is clicked
Vbno 7 No button is clicked.
If the message box is used with out return value then syntax is
Msgbox "message”, dlgdef, ”title
So we do not use any brasses after the msgbox reserve name.

2. Input Dialog Box: -

This box is used to receive the input form the user during the execution of program.
Syntax: -
[Variable name]=Input box (prompt, title, default x pos, y pos)
Where prompt is string constant or string variable
Title is Title, which appear on the title bar of the box.
Default is the text, which appear in the text box of the input box already.
X and y are two points on the form where the specific input box is appear.

Transfer of Control in VB

All the statements in a program are executed in order in which they are written. But if we want to change the execution order we use transfer of control statement.
There are two types of transfers of control.
1) Unconditional Transfer of control

2) Conditional Transfer of control
1) Unconditional Transfer Of control: -
When we want to transfer the control one statement to other statement with out specifying any condition at any time we use Unconditional Transfer of Control.
GOTO statement is best example of Unconditional transfer of control.
GOTO Statement: -
This statement is use to transfer the control form one statement to other statement unconditionally.
Syntax: - GOTO Label
This statement transfers the control to the specific label statement.
When control is reach to GOTO statement control not transfer back to the line at which we transfer the control.

2) Conditional Transfer Of Control: -

a) Selection Structure: -

In this structure first we test the condition and if condition is true then control is transfer to given location. Followings are three types of selection structure.
 Nested IF—THEN—ELSE Statement

IF THEN Structure in VB

IF- Then Else structure is also called single selection structure. This structure execute the statement or set of statement after the IF statement (if the condition is true) and ignore this statement if the condition is false.
Syntax: -
IF (Condition) Then
Visual Basic Statment1
Visual Basic Statment2
End IF
For example
IF( A >= 100) Then
Print "Hello VB”
End If


In IF structure if the condition is true then after IF, set of statements is executes and if the condition is FALSE then nothing will be executed.
In this structure on condition and two block of statement are given one is after if statement and other is after else statement. If the condition is true then after IF statement block of statements are executed and if the condition is FALSE then after the ELSE block of statement are executed.
IF (Condition) Then
VB Statements
VB Statements
End If

Nested If Then Else in Vb

If we have to test the multiple conditions then we use nested IF-Then-Else structure. In this structure one IF statement is placed in the body of other IF statement.
Syntax: -
If (Condition) Then
VB Statements
If (Condition) Then
VB Statements.
VB statements
End If
End if
Note: - Every " IF " statement has its own " END IF " statement.
An other way of using Nested if then else statement is.
If (Condition) Then
Elseif(condition) then
Elseif (condition) then
End if

Note: - In this structure END IF statement is used in the END only One time.

Select statement in VB

This is another form of the multi way decision making. It is well structured. The IF–THEN-ELSE structure is very easy when only one condition is used but when more then one conditions are used then this structure is very complicated. In such situation we used Select Structure. Select structure is used where one condition and many choices are given. This structure is batter then the IF–THEN-ELSE structure.
Syntax: -
Select Case Expression Case Expression1
Visual Basic Statement
Case Expression1
Visual Basic Statement
Case Expression1
Visual Basic Statement
Case Else
Visual Basic Statement
End Select
Switch statement work similar as nested if statement works.

Loop Structure in VB

Other way of conditional transfer of control is called Loop Structure. When one or more then one statement are executed more then one time or we say when we want to execute some statement repeatedly in same way then we use loop structure called loop.
Loop structure is very important for any programming language.
Visual Basic has following different types of loop structure.

For Next Loop in Vb

This loop is count control loop. In this loop structure loop is executed for specific number of time .In this loop we specify the initial value and final value every time loop count the number if the number is grater then the final number then loop is terminated.
Syntax: -
For count-variable= Initial value To Final-value step [increment]
Visual Basic Statements
Next [Count-variable]
Count-variable is variable counter. Which store the number of repetition of the loop.
Initial value specifies the Starting value of counter variable.
Final-Variable specifies the end value of loop where loop is terminated.
Increment is specifying the increase/decrease in the value of counter variable after
each repetition.
Steep value or increment is optional if not specify then counter is increase one by one.
For example if we want to print the Number between 1 to 100 on Form then we use following set of statement.
For x = 1 to 100
Print x
Next x
Where x is an integer variable, which is used as counter variable in this loop structure.

While Wend Structure in VB

While Wend is event control loop in this structure a condition is given in Head of Lop. In this loop first condition is tested if condition is true then after while and before wend set of statement are executed and control transfer again to while statement and again condition is tested if condition is false loop is terminated and control transfer after the wend statement.
Syntax: -
While (Condition)
Statement 1
Statement 2

Do while Loop in Vb

The Do-While loop is event control loop. In this loop all the statement, which are, write in body of loop are executed, as the condition is true.
In this loop first of all condition is tested and if condition is true then after while and before loop all statement are executed. If condition is false then control immediately transfer after "loop” statement.
Do While (Condition)
Visual Basic Statment1
Visual Basic Statment2
Visual Basic Statment3

Do Until Loop in Vb

This loop is also event control loop. In this loop we specify the condition in the start of the loop first condition is tested and its works as long given condition is false.
Syntax: -
Do Until (Condition)

5. Do –Loop While: -

This loop is similar to Do-While Loop but in Do While Loop first we specify a condition and first of all condition is tested, if the condition is true then loop is execute. But In DO Loop While first set of statements are execute and then condition is tested .So we say that in this loop structure all statement in body of loop are executed at least on e time.
Syntax: -
Loop While (Condition)

Do-Loop Until in VB

This loop structure is same as do until loop expect that the condition is tested at the end of the loop structure and loop statement are executed as long as the given condition remains false.
Syntax: -
Loop until (condition)
In this structure first of all given statements in body of the loop are executed and the condition is tested if condition is false then control again transfer back to do statement and if condition is true then loop is terminated and control transfer to the loop until statement.

Arrays in VB

Array is powerful type of data structure, which stores the same type of data in consecutive memory location.
If we want to store the marks of 100 students in memory then we have two ways
First we define 100 variables and then give the value to every variable.
Like that S1=99
S3=80 and so on
Which is difficult process.
Second one is we Use array for this purpose.
In array structure storage location identified by a name which is called array name. The data item of array are called element of array and each data item are store in separate memory location. Each location in array is identified by its position value, which is called index value.
Now in above case if we want to store 100 marks of different student by using array we define array of 100 items.
S (100) As Integer
Where S is name of array and total element are 100.
There are two type array used in visual basic
1) One Dimensional Array
2) Two or Multi Dimensional Array

One Dimensional Array in VB

One-dimensional array is also called List, vector or linear array. It is used to store the similar data in continues memory location in shape of one row or one column.
Declaration Of One Dimensional array:
In declaration of array we must define array Name, Data type and total element of array. In visual Basic array is explicitly declared by using Dim, Public or Static statement according to scope of array and a keyword as is Use for specifying the data type.
Dim name (n) As data type
For example if we declare array named month of 12 element of string data type then we define. Dim month (11) As sting
In VB array is Zero-based. Its means that first element of array has 0 index value, but we also define that first index value is start form 1By defining option base statement in declaration section.
Option Base 1
Dim days (1to 7) As sting
"To” be a keyword is specifying that 7 elements are used in this array and first index value is last is 7.
Assigning value to Array:
For assigning value to array we used assignment statement, or loop structure.
For example in assignment statements
Name (0) = " Tauqeer ”
Name (1) = "Shah”
Name (2) = " Marriam”
And with loop structure we define array and give the value with one assignment statement instead of separate assignment structure.
Dim Name(10) integer
For I = 0 to 9
Name(1) = I+1
Print num (1)

Two or Multi Dimensional Array in VB

Two-Dimensional array is also called table or a matrix or we say when an array consist on more then one row and columns then it is called two or Multi - Dimensional array. Two-dimensional array have two subscript in the name of array.
For example Sname(4,4)

Where one subscript represent the row and other represent the column.
Declaration of two Dimensional arrays
Two-dimensional array declare in the same way as one-dimensional array is declare.
Dim variable-name(R, C) As Data-Type
For example:
Dim NUM (3,4) As Integer
These arrays further classified in to two types:
1) Fixed-Size Arrays (Static Array)
2) Dynamic Arrays
3) Control Array

Fixed-Size Arrays (Static Array) in Vb

When an upper bound is specified in the declaration, a Fixed-array is created. The upper limit should always be within the range of long data type.
Declaring a fixed-array
Dim numbers (5) As Integer
If we want to specify the lower limit, then the parentheses should include both the lower and upper limit along with the To keyword. An example for this is given below.
Dim numbers (1 To 6) As Integer
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6.

Dynamic Arrays in VB

Basically, you can create either static or dynamic arrays. Static arrays must include a fixed number of items, and this number must be known at compile time so that the compiler can set aside the necessary amount of memory. You create a static array using a Dim statement with a constant argument.
Most programs don't use static arrays because programmers rarely know at compile time how many items you need and also because static arrays can't be resized during execution. Both these issues are solved by dynamic arrays. You declare and create dynamic arrays in two distinct steps. In general, you declare the array to account for its visibility (for example, at the beginning of a module if you want to make it visible by all the procedures of the module) using a Dim command with an empty pair of brackets. Then you create the array when you actually need it, using a ReDim statement:
For Example: :
Dim marks( ) as integer:
Private Sub Command1_Click ():
ReDim marks (3) :
End Sub:

Control Array in VB

A group of control that shares a common name, type, and event procedure is called control array. All control arrays have the same name and same procedure but they all have different index property.
Where index property is numeric value. It starts from 0 for the first control and increase for each subsequent control in the array.
This property specifies in procedure that which property has clicked.
Procedure of creating a control array
 To create control array on the form
 Start a new exe project
 Draw a control on the form and set all properties.
 Copy control to clipboard.
 Past the control on the from form the clipboard.
 A message appears.
" Do you want to create a control array "
Click yes for create control ar
ray and no for create new control.
Adding Code
As we know that all control of array having same name. So they will execute same procedure and same event to perform on control.

Procedure And Function in VB

When you want to perform a specific task most time in the project then you write every time same procedure. (e.g) If you want to calculate power of nay digit so you write procedure for this specific function but other easy way is sub program, which is single alone complete and independent program. It is executed by other procedure to perform specific task.
Types of Subprogram
There are two types of Sub Program in Visual Basic.
1) Subroutines / Sub procedure
2) Function

1. Subroutines: -

It is type of subprogram, which consists of a block of statement that carries out well-defined task. It is also called sub procedure or procedure. This procedure does not respond to any event. They are called standard procedure to distinguish them form event procedure. Sub procedure written either in the code windows or module of a form or in external module.
They are executing by other procedure by calling statement.
Scope Sub Procedure-Name (Argument separated by Commas)
Scope specify the scope of procedure
Sub is reserved /key word Specify the sub procedure.
Procedure name is any valid variable name, which specifies the name of procedure, and procedure is called by this name.
Arguments are the list of variable passed to the procedure. A sub procedure may have some argument then they must be declared and there type also declared.
We also pass an array through the argument to Sub Procedure.
Calling Of Sub Procedure: -
A Sub Procedure is executed by other procedure or standard procedure so the procedure that execute the sub procedure is called calling procedure. It is execute the sub procedure by CALL Statement.
Syntax: -
Call Procedure-Name (Arguments)
The variables Used in calling function are called two way variable.

2. Function

Function is an independent procedure that is written to perform a specific task. It is also Non-Event procedure. Function returns a single value to procedure that executes it.
Syntax: -
Scope Function Function-Name (Arguments with type) AS Type
Scope specifies the scope in which as called.
Function name is any valid VB variable name.

Scope of Sub-Program
There are two types of scope used in sub program PRIVATE and PUBLIC.
Private Declaration of sub program is called by the procedure in same module in which they are defined.
If we   declare any sub procedure as Public than it called any procedure from any where in the project.

Built-in Function in VB

Visual Basic has variety of built-in function, which perform specific task. When we want that specific work than we just call that function, there is no need of further coding.
These functions divide in to following type.
1) Number Function
2) String Function
3) Date and Time Function
4) Conversion Function
5) Formatting Function

String Function in VB

InStr Function: -

This function Search a string in base string and return integer value, which show the position of searched string.
Syntax inster(start, base string, searching string)
Where start is position where form search is started and base string is real string in which search is made and searching string is that string which we want to search.
For example:- InStr(1,”Toqeer”,T)
This function returns 1 as T is appear in first location is base string.

1. InStrRev Function: -

This function work as InStr function works but it search the string firm end of the base string.
Syntax inster(base string, searching string,start)
Where start is position where form search is started and base string is real string in which search is made and searching string is that string which we want to search.
For example:- InStrRev(”Toqeer”,”r”,-1)
This function returns 5 as R is appear in first location is base string.

LCase function converts the given string in to lower case and UCAse Convert The given string in to upper Case.
Syntax:- Lcase("string”)
For example Lcase("TOQEER SHAH”) or Ucase("String”)
This function return "touqeer shah”

3. Left function: -

This function returns the Left most character of the string.
Syntax: - Left("String”,Length)
Where String is given text and Length is integer number which show that how many character are displays form left side.

4. Len Function: -

This Function returns the total Length of the string.
Syntax: - Len ("String”)

6. Like Function: -

This function match true string if the string match then its return TRUE other wise FALSE.
For Example
S= "Toqeer” like "Tanveer” then "S " Return FALSE.

Replace Function: -

Replace function replace the selected string with other string.
Replace (String, String Find, String Replace, [Start up Position], [ VB Compare Method] )
For example Replace ("Dikhan is my Country”,”Dikhan”,Pakistan”)
Replace the word "Dikhan” with "Pakistan”

7. SPC Function:-

This function put the spaces in two or more then two string.
Syntax: - Spc(Number)
For example:- Print "Toqeer ” ; spc(10) ; "Shah”
Above statement print Toqeer Shah and give 10 spaces in both strings.

StrComp Function:

This Function compares two strings and then gives the result.
Syntax: StrComp("String”,”String”,VbCompare Method)
StrComp("Pakistan”, "Pakistan”) then result of comparision is return 0 means that first string and 2nd string are same.
StrComp("Pakistan”, "Pakistan”) then result of comparision is return 1 means that first string is grater then 2nd string.
StrComp("Pakistan”, "pakistan”,vbTextCompare) then result of comparison is return 0 means that first string and 2nd string are same.


1. Abs Function:-
This Function return the absolute value of any number.
Syntax: ABS(number)
Form example ABS(-200) Return 200
2. Sin and Cos Function:
These function return the Cosine and sine Value of given number
For example Cos(0)=1
3. Fix Function: -
This Function removes the Fraction part of the number.
For example Fix (10.234) Return 2
4. Int Function: -
This function return the largest integer value less than or equal than to a number.
For example int (3.8) return 3 and int(-3.8) return 4
5. Rnd Function:-
This function returns the single integer value form group of number.
Syntax:- int ((I max – I min +1) *RND)+Imin

6. Sign Function:-
This function tell about that number is +ve or –ve . if number is +ve then it return 1 and if number is –ve then it return –1 and 0 if the number is zero.
7. Sqr Function :-
This Function return the Square root of the number,
For example Sqr(9) is 3

Date And Time Function in VB

Date Function:-
Date Function it returns the current date of the system.
1. Time Function:
This function returns the Current time of the System.
2. DateAdd Function:
This function adds the current interval of time in date.
Syntax: DateAdd(interval, number, date)
For example DateAdd("d”,10,date())
This function adds 10 days in current date of the system. We also use month (m) as interval and year (y) as interval.
3. DatePArt Function: -
This Function returns the part of date.
Syntax:- DatePart(interval,date)
For example DatePart("d”,#16/10/05#) Return 16 which is day of given date. We can also use m and y for Yare and Month.
4. DateDiff Function:
This function calculates the total difference between two dates.
Syntax:- DateDiff(interval, date1, date2)
Day Function:
This Function returns the day from given date.
Syntax:- Day(date)
5. IsDate Functon:
This Function check that given string is Date Or Not.
Syntax:- IsDate(expression)
6. Month Function:
This function returns the month from given date.
7. WeekDay Functin: This Function returns the day of the week.
For example WeekDay(#05/10/2005#) retyrn 6 (where 6 represent Friday)
8. WeekDayName Function:-
This Function return the day by name from given date
9. Year Function:
This function return the year from given date

Conversion Function in VB

1. Asc function:
This Function returns the ASCII code of given character.
2. Char Function:
This Function return the character of given ASCII code
3. IsNumeric Function:
This Function is used to check the given string and return TRUE if the string is Number other wise return FALSE .
4. Val Function:
This Function convert the date data type in to number.
Formatting Function:
These type of function are used to format the date, time and number according to predefine order.
For example Format (1234,”Curency”) return $1234 and in same way format (0,”on/off”) return Off.
Some important and most commonly used formats are
Format(Now,”dddd”)èReturn Wednesday
Format(Now,”C”)èReturn time
Format(1.234,”0”))èReturn 1
Format(14/08.05,”dd-mmm-yy”)èReturn 14-aug-05

Visual Basic Graphics

Types of graphic
Visual Basic has two types of graphic. These are,
1) Vector Graphic
2) Bitmap Graphic
1. Vector Graphics: -
The image garneted by the graphic command or method available in visual basic is the vector graphic. For example Line, Circle
2. Bitmap Graphic: - The image that is displayed on the various control and processed as Pixels are called bitmap graphic.
The main different between vectors graphic can be drawn on any monitor resolution of any size with same quality on the other hand Bitmap graphic depend on the resolutions of monitor. Bitmap graphic are quite useful and more commonly used then Vector graphic. Both graphic can be mixed to produce a required shape.
Color Control In Visual Basic:
All the graphic method may use color argument. The color is specified in Hexadecimal number (Long Integer number). For example Red Have a value &H0000FF&.
This is difficult to remember these values so we can also used V.B Symbolic Constant.
1. Symbolic Constant: -
V.B used eight Symbolic Constant for color.

VB Black	Black Color
VB Red	Red Color
VB GREEN	Green Color
VB Yellow	Yellow Color
VB Blue	Blue Color
VB Magenta	Magenta Color
Vb Eyen	Eyen Color

2. QB Color Function: -
The QB Color Function also used in visual basic as color argument. It have there own color constant.
Syntax: -
Qbcolor(Index value)
For example

0	Black	8	Gray
1	Blue	 9	Light Blue
2	Green	10	Light Gray
3	Eyen	11	Light Eyen
4	Red	12	Light Red
5	Magenta	13	Light magenta
6	Brown	14	Yellow
7	Whit	15	Bright White

The color function can be used to produced one over 16 million color.
Syntax: -
RGB (Red, Green, Blue)
Where red green blue are integer, which specify the intensity of the color. These values can range from 0 to 255.
For Example For Yellow color use,
RGB (255, 255, 0)

Graphic Controls in Visual Basic

Graphic Controls are used to draw graphic on the form. There are five controls in Visual Basic.
1. Image Box: -
Imago Box is used to display the image, which are already store on any storage device of the computer. This control can be display following type of image.

BMP	(Bit Map Picture) 
ICO	(Icon File)
WMF	(Window Meta File)
GIF	(Graphic Image Format)
JPG	(Joint Photograph)

Image can be placed on the form anywhere as we placed other control.
Properties of the image Box: -
Picture: -
In this property we specify the name of any graphic picture file with complete path.
It can also be load in the image Box at run time with load picture method.
Image. Picture=loadpciture (file name with complete path)
Stretch: -
This property has two values True and False. If set True than image stretched / reduced to cover whole size of image box.
Adding Image Through Clip Board: -
We also add the image through the clipboard (Through copy and paste method). Process is given below.
1) Draw image box control.
2) Copy image form anywhere.
3) Select the image box.
Paste the image.

2 Picture Box: -
The Picture box control is similar to image box control. It is used for following purpose.
To display the image files but it is differ form the image box. The difference is that it has great flexibility and control over image. A picture box also required more memory then image box.
A picture box contains also other control. If picture box move then all control on the box also move together.
It can also used for grouping graphics together to design a shape.
Properties of picture box: -
Auto Size:
This property used to specify whether or not the control automatically resizes when picture is large then the control size. This property works on two value True and False.
Border style:
This is used to set the border style No border display if borer property is set to none.
Picture: -
In this property we specify the name of any graphic picture file with complete path.
It can also be load in the image Box at run time with load picture method.
Picturebox. Picture=loadpciture (file name with complete path).
3. Shape Control: - Shape control are used to create predefine shape on the form or also on the other control like that picture box. With the help of shape control we create Rectangle, Square, Oval, Rounded Rectangle and Rounded Square shape can be created.
Properties: -
Fill style:
The properties is used to fill the shape with one of the predefine pattern.
Border style:
This property is also have some predefine border style we can select one of them. Graphic Method / Vector graphic
Print Method: -
It is used to print information on the form or picture box.
Object name. Print ("information”)
The information can be a variable, text, and expression. If no object is define or specify then printing is done on the form.
We also used Current x and current y and color and font with print.
Where current x and current y are two variables which contain two coordinates point for any graphic shape of the operation.
For example
Current x= 200
Current y= 200
Print "Hare is point "
Line Method:

The line Method is used to draw lines and box.

Object name. Line (x1, y1)-(x2, y2), color, B, F
Where x1, y1 are two starting pint of line and x2, y2 are ending point.
Color is color of line.
B is used to draw a box instead of simple line.
F is used to fill the box with same color of line.
CLS Method:
Cls clear the graphic from the object.
Object name. cls
Move Method:
It is used move an object on the form from one location to an other location.\
Object name. Move left, top, and width, Height
With and height are both optional and specify the new height and width
Top specifies the y coordinate.
Left specifies the left coordinate.

Advanced Active X Control in Visual Basic

Visual Basic also provides several Active X controls that are used to develop advanced application program such as word processor, Spreadsheets and graphics application program. These control not available in toolbox by default but we can add these control in toolbox by taking some simple steps.
Following are some more co