VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5...

25
Page | 1 Prepared By:- Ankit Shah Visual studio is complete package of development tools for developing web application, desktop application, mobile application etc. For developing any type of software in visual studio .Net we have to select the language. .Net support 20 language for developing software Some common languages are …. Visual Basic .Net Visual C++.Net Visual C#.Net Visual J#.Net Some common types of project that we can develop in Visual studio .Net are as below. o ASP.Net web application(Dynamic web site) o Windows Forms based application o Console application(DOS base) o Smart device application(Mobile application) o Class Library(Business logic for 3 tier) o Web or windows custom controls(Own Controls) o Web services Version o 1. 0 visual studio .Net o 1.1 visual studio .Net 2003 o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform for building, developing and running application The .Net consists of 2 main parts: Common language runtime Class libraries What is common language Runtime? o It is the execution engine for .Net framework application. o It is the heart or backbone of the .Net o It is the runtime engine provided by the .Net framework. o It provides an infrastructure for run program and allows them to communicate with other parts of the .Net framework. What is common type system? o CTS allows program written in different programming language to easily share information. o CTS provides cross language integration. What is common language specification? o CLS includes basic language features needed by almost all the application. o It serves as a guide for library writers and compiler writers. o The common language specification is a subset of the common type system. o The common language specification is also important to application developers who are writing code that will b/w used by other developer. VB.NET .Net Platform (Framework)

Transcript of VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5...

Page 1: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 1

Prepared By:- Ankit Shah

Visual studio is complete package of development tools for developing web

application, desktop application, mobile application etc.

For developing any type of software in visual studio .Net we have to select the

language. .Net support 20 language for developing software

Some common languages are …. Visual Basic .Net

Visual C++.Net

Visual C#.Net

Visual J#.Net

Some common types of project that we can develop in Visual studio .Net are as

below.

o ASP.Net web application(Dynamic web site)

o Windows Forms based application

o Console application(DOS base)

o Smart device application(Mobile application)

o Class Library(Business logic for 3 tier)

o Web or windows custom controls(Own Controls)

o Web services

Version o 1. 0 visual studio .Net

o 1.1 visual studio .Net 2003

o 2.0 visual studio 2005

o 3.0

o 3.5 visual studio 2008

o 4.0 visual studio 2010

The .Net framework is a service or platform for building, developing and running

application

The .Net consists of 2 main parts:

Common language runtime

Class libraries

What is common language Runtime?

o It is the execution engine for .Net framework application.

o It is the heart or backbone of the .Net

o It is the runtime engine provided by the .Net framework.

o It provides an infrastructure for run program and allows them to communicate

with other parts of the .Net framework.

What is common type system?

o CTS allows program written in different programming language to easily share

information.

o CTS provides cross language integration.

What is common language specification?

o CLS includes basic language features needed by almost all the application.

o It serves as a guide for library writers and compiler writers.

o The common language specification is a subset of the common type system.

o The common language specification is also important to application developers

who are writing code that will b/w used by other developer.

VB.NET

.Net Platform (Framework)

Page 2: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 2

Prepared By:- Ankit Shah

.NET Framework

What is assembly?

o An assembly is the primary building block of a .Net framework application.

o An assembly is a logical DLL.

o It consists of DLLs or executables.

o It is a collection of functionality that is built, versioned and deployed as a

single implementation unit.

What is private assembly and shared assembly?

o A private assembly is used only by a single application, and is stored in that

application’s install directory

o A shared assembly is one that can be referenced by more than one application.

o In order to share an assembly, the assembly must be explicitly built for this

purpose by giving it a cryptographically strong name.

What is metadata?

o Metadata stores within the assembly.

o Metadata means data about data.

o A .Net language compiler will generate the metadata and stores this in the

assembly.

o On the .Net platform programs are compiled into .NET PE(portable executable

)files.

o Metadata is nothing but a description of every namespace, class, method,

property etc. contained within the PE file.

o The CLR uses this metadata to

o Locate classes, Load classes, Generate native code, Provide security

Page 3: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 3

Prepared By:- Ankit Shah

What is .Net framework class library?

o In C, <conio.h> etc. are header files. We add those header files in our program

to use inbuilt function.

o Same hear, the .Net framework are collection of classes or namespace that can

be used to develop application.

o The class library consist of data classes, XML classes, web forms classes and

window forms based classes, smart device classes, input-output classes.

o Other name of FCL is BCL(Base class library)

What is namespace?

o As above, the .Net framework class library is collection of namespace.

o Namespace is a logical naming scheme for types that have related functionality.

o Namespace is nothing but a logical container or partition.

o It’s like drive of out computer.

o Like my computer contain C: , D:, E: , F: my F: drive contains songs and video

and C: contains installed file so on.

o For example my friend wants songs. So I will directly go to my computer’s F:

because songs are places there.

o As the root of the hierarchy is the system namespace.

o The notion of a namespace plays a fundamental role in the .Net framework.

o Common namespace:

System

Contains fundamental classes and base classes.

System.Data

Contains system classes for database connection.

System.IO

Contains classes for reading and writing data in file.

What is garbage collection?

o Garbage collection is a mechanism that allows the computer to detect when an

object can no longer be accessed.

o It then automatically free up the memory used by that object.

o One of the advantages of CLR is automatic memory management that uses the

garbage collection mechanism.

o The CLR’s garbage collector GC manages the allocation and release of

memory for an application.

Write down managed execution process of .Net program?

Program execution of VB.Net

Select compiler

For VB.net select VBC compiler for C# select CSC same as for all

language wise select compiler.

VBC stands for visual basic compiler.

Compile code to MSIL

Converting your source code into MSIL and generates the metadata.

MSIL to native code

JIT compiler translates the MSIL into native code.

Run your code

What is Microsoft intermediate language?

o MSIL is the CPU independent instruction set into which .Net framework

programs are compiled.

Page 4: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 4

Prepared By:- Ankit Shah

o It contains instruction for loading, storing, initializing and calling methods on

object.

o Combined with metadata and the common type system, MSIL allows for true

cross-language integration.

o MSIL also known as CIL common Intermediate language of IL intermediate

language.

What is JIT?

o It stands for “just in time.

o It’s a smart compiler.

o JIT does not compile whole program each time and every time. It compile only

that portion of the program which functions are called that time. And suppose

native code is already present then that data will not again compiled. If changes

are made then possible that it will again generate MSIL to native.

o Firstly any program compile by its own compiler then it will convert into MSIL

then with the help of the JIT; MSIL compile into native code but CLR does not

convert whole MSIL code to native code on Load time of that application;

instead of it compiles the MSIL instruction as they are called.

o There are 3 type of JIT.

Pre-JIT

It compiles complete program into native code in a single compilation

cycle. This process is done at the time of deployment of the program.

Econo-JIT

It compiles only those methods that are called at runtime.

Normal-JIT

It’s like econo-JIT. The methods that are compiled the 1st time they are

stored in cache. When the same methods are called again the compiled

code from cache is used for execution.

The Common Language Runtime, also known as the CLR, is the heart of .NET. The

Common Language Runtime takes your .NET application, compiles it into native

processor code, and runs it. It provides an extensive range of functionalities for

helping the applications run properly, so look at each one in turn.

❑ Code loading and execution

❑ Application isolation

❑ Memory management

❑ Security

❑ Exception handling

❑ Interoperation

Code Loading and Execution

This part of the Common Language Runtime deals with reading the MSIL code

from the disk and running it. It compiles the code from MSIL into the native

language (machine code) that the processor understands.

Java also has a concept similar to MSIL, known as byte code.

Common Language Runtime

Page 5: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 5

Prepared By:- Ankit Shah

Application Isolation

One important premise of modern operating systems like Windows and Linux is

that applications are isolated from one another. This is critically important from

both security and stability standpoints.

Imagine that you have a badly written program and it crashes the PC. Should this

happen? No, you want only the badly behaved program to crash, as you do not

want other applications or the operating system itself to be affected by a program

running on it. For example, if your e-mail program crashes, you do not want to

lose any unsaved changes in your word processor.

With proper application isolation, one application crashing should not cause

others to crash.

This level of application isolation is already available in Windows. .NET extends

and enhances this functionality by further improving it.

Security

.NET has powerful support for the concept of code security. This was designed to

give system administrators, users, and software developers a fine level of control

over what a program can and cannot do.

Interoperation

Interoperation in the .NET Framework is achieved on various levels.

One kind of interoperation is at the core of the framework, where data types are

shared by all managed languages. This is known as the Common Type System

(CTS). This is a great improvement for language interoperability.

Exception Handling

Exception handling is the concept of dealing with “exceptional happenings” when

you are running the code.

Imagine that you have written a program that opens a file on disk. What if that file

is not there? Well, the fact that the file is not there is exceptional, and you need to

deal with it in some way. It could be that you crash, or you could display a

window asking the user to supply a new filename. Either way, you have a fine

level of control over what happens when an error does occur.

.NET provides a powerful exception handler that can “catch” exceptions when

they occur and give your programs the opportunity to react and deal with the

problem in some way.

Option Explicit— Set to On or Off. On is the default. Requires declaration of all

variables before they are used (this is the default).

Option Compare— Set to Binary or Text. This specifies if strings are compared

using binary or text comparison operations.

Option Strict— Set to On or Off. Off is the default. When you assign a value of

one type to a variable of another type Visual Basic will consider that an error if

this option is on and there is any possibility of data loss

Page 6: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 6

Prepared By:- Ankit Shah

Visual Basic Statements

A Visual Basic statement is a complete instruction. It can contain:

Keywords—Words reserved for Visual Basic's use.

Operators—Symbols used to perform operations, like +, which performs addition

operations; -, which performs subtraction operations; and so on.

Variables—Symbolic names given to values stored in memory and declared with

the Dim keyword. For example, if you've declared a variable named temperature

as an Integer type, you can store integer values like 72 or 83 in it.

Literal values—Simple values, like 5 or "Hello."

Constants—The same as variables, except that constants are assigned a value that

cannot then be altered.

Expressions—Combinations of terms and/or keywords that yield a value. For

example, if the variable temperature holds the value 72, then the expression

temperature + 3 yield the value 75.

Declaring Constants

When it’s time to change those values, you just change the constants, all in one

well-defined part of the code. How do you use constants? You declare constants in

Visual Basic with the Const statement:

[Public | Private] Const constname [As type] = expression

The Public keyword is used at the module level to make a constant global. This

keyword is not allowed in procedures.

The Private keyword is used at the module or form level to declare constants that

are private, which means only available within the module or form where the

declaration is made. Like the Public keyword, Private is not allowed in procedures

(constants in procedures are always private anyway).

The constname identifier is the actual name of the constant. The type identifier is

the data type of the constant, which may be Byte, Boolean, Integer, Long,

Currency, Single, Double, Date, String, or Variant. The expression identifier

holds the value you want for this constant.

Here’s an example showing how to declare and use a constant:

Private Sub Command1_Click ()

Const Pi = 3.14159

End Sub

Declaring Variables

Usually, you use the Dim statement to declare variables, although you can also

use the Private (declare a private variable), Public (declare a global variable),

Static (declare a variable that holds its value between procedure calls), ReDim

(redimension a dynamic array), or Type (declare a user-defined type)

keywords to declare variables.

Page 7: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 7

Prepared By:- Ankit Shah

The Dim Statement

Here’s how you use the Dim statement:

Dim [Var_Name] As [Var_Type]

Here’s an example of declaring variables using Dim:

Dim a As Integer

Dim EmployeeName As String

Dim EmployeeAddress As String

What Data Types Are Available?

There is a wide range of data types. The Visual Basic variable types appear in Table

for reference, making selecting the right type a little easier. Note that the Single and

Double types handle floating point values, which the Integer types. (such as Short,

Integer, and Long)You might also notice that there are some new types in VB .NET

that weren't in VB6, like Char, and that some other types, like Currency or Variant,

are gone. Note in particular the Boolean data type, which takes values like True or

False only—also called logical values.

Table: Visual Basic data types.

Type Storage size Value range

Boolean 2 bytes True or False

Byte 1 byte 0 to 255 (unsigned)

Char 2 bytes 0 to 65535 (unsigned)

Date 8 bytes January 1, 0001 to December 31, 9999

Decimal 16 bytes

Double 8 bytes

Integer 4 bytes -2,147,483,648 to 2,147,483,647

Long 8 bytes

Object 4 bytes Any type can be stored in a variable of type

Object

Short 2 bytes -32,768 to 32,767

Single 4 bytes -3.402823E to -1.401298E-45 for negative

values; 1.401298E-45 to 3.402823E for positive

values

String Depends on

implementing

platform

0 to approximately 2 billion Unicode characters

User-

Defined

Type

(structure)

Sum of the sizes of its members. Each member of the structure has a

range determined by its data type and independent of the ranges of the

other members (Structure, Array, Enum)

Page 8: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 8

Prepared By:- Ankit Shah

There are various types of operators in Visual Basic, and I'll go over them all here.

Here are:

Arithmetic operators:

^ Exponentiation

* Multiplication

/ Division

\ Integer division

Mod Modulus

+ Addition

- Subtraction

Assignment operators:

= Assignment

^= Exponentiation followed by assignment

*= Multiplication followed by assignment

/= Division followed by assignment

\= Integer division followed by assignment

+= Addition followed by assignment

-= Subtraction followed by assignment

&= Concatenation followed by assignment

Comparison operators:

< (Less than)—True if operand1 is less than operand2

<= (Less than or equal to)—True if operand1 is less than or equal to

operand2

> (Greater than)—True if operand1 is greater than operand2

>= (Greater than or equal to)—True if operand1 is greater than or equal to

operand2

= (Equal to)—True if operand1 equals operand2

<> (Not equal to)—True if operand1 is not equal to operand2

Is—True if two object references refer to the same object

Like—Performs string pattern matching

String Concatenation operators:

& String concatenation

+ String concatenation

Logical/Bitwise operators:

And— Performs an And operation (for logical operations: True if both

operands are True, False otherwise; the same for bit-by-bit operations where

you treat 0 as False and 1 as True).

Types of Operators

Page 9: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 9

Prepared By:- Ankit Shah

Not— Reverses the logical value of its operand, from True to False and False

to True, for bitwise operations, turns 0 into 1 and 1 into 0.

Or— Operator performs an Or operation (for logical operations: True if

either operand is True, False otherwise; the same for bit-by-bit operations

where you treat 0 as False and 1 as True).

Xor— Operator performs an exclusive-Or operation (for logical operations:

True if either operand, but not both, is True, and False otherwise; the same

for bit-by-bit operations where you treat 0 as False and 1 as True).

AndAlso— Operator A "short circuited" And operator; if the first operand is

False, the second operand is not tested.

OrElse— Operator A "short circuited" Or operator, if the first operand is

True, the second is not tested.

Miscellaneous operators:

AddressOf— Gets the address of a procedure.

GetType— Gets information about a type.

VB6 programmers will note a whole new set of assignment operators, such as +=, -=,

and so on. Following the lead of languages like Java, VB .NET now supports these

combination operators. For example, += is a combination of + and =, which means

that you can write intValue1 = intValue1 + 1 as intValue1 += 1. In a similar way,

you can write intValue1 = intValue1 * 5 as intValue1 *= 5, providing an easy

shortcut.

Also, in Visual Basic .NET, if the first operand of an And operator evaluates to False,

the remainder of the logical expression is not evaluated. Similarly, if the first operand

of an Or operator evaluates to True, the remainder of the logical expression is not

evaluated. This is called short-circuiting.

Conditional Logic Statements (Control / Decision Structure)

If … Then

If … Else … EndIf (If … Then … Else)

If … ElseIf … EndIf (If … Then … ElseIf)

Select Case

Looping (Iteration) Statements

Do … Loop

Do While

While Wend

Loop While

Do Until

Loop Until

For…Next

Conditions & Loops

Page 10: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 10

Prepared By:- Ankit Shah

Conditional Logic Statements

If . . . Then

If...Then statement is used to redirect program flow based on the results of a

conditional test. There are two forms of the If...Then statement: single line and

multiline. You should only use the multiline statement because it’s much easier to

read.

Here’s the single-line syntax:

If <Cond> Then <Statement>

<Cond> can be any expression that evaluates to a True or False value. True is

defined as any nonzero number, such as 1, 1, 2, 500, and so on. False, on the other

hand, is zero (0).

Here’s an example:

If txtLast.Text = "" Then

MsgBox "Last Name Must be Filled In"

If . . . Then . . . End If

The multiline form of the If...Then statement is terminated with an End If

statement. You need to use the End If statement if you have multiple lines of code

in between the If and End If statements.

Here’s the multiline syntax:

If <Cond> Then

<Statement Block 1>

<Statement Block 2>

<Statement Block ...>

<Statement Block n>

End If If … Else … EndIf (If … Then … Else)

The Else Clause

The If statement also allows you to add an Else clause you can use to execute a

different set of code if the condition evaluates to a False condition. Heres an

example:

Private Sub Button1_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles Button1.Click

If RdoMale.Value = True Then

MsgBox "Employee is Male"

Else

MsgBox "Employee is Female"

End If

End Sub

Page 11: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 11

Prepared By:- Ankit Shah

In this example, the code between Else and End If is executed if

RdoMale.Value is set to False.

The IIf( ) Function

The IIf() function allows you to combine an If...Then...Else statement

into one line. The IIf() function accepts three parameters. If the first parameter

evaluates to a True condition, the value of the second parameter is returned. If the

first parameter evaluates to a False condition, the value of the third parameter is

returned.

Here’s the syntax:

IIF(<Cond1 is True>, <Return Exp1>, <Else Return Exp2>)

Here’s an example:

Dim intTemp As Integer

intTemp = IIf(boolPerform, 1, 0)

If … ElseIf … EndIf (If … Then … ElseIf) The ElseIf Clause

If you have multiple conditions to check, you can also use the ElseIf clause. Each

condition is checked until a True condition is found. Once the True condition is

found, the code within the block between the ElseIf and the next ElseIf or End

If statement is executed. After executing the block of code, the next line executed

will be after the End If statement.

Here’s the syntax:

If <Cond1> Then

<Statement Block 1>

[ElseIf] <Cond2> Then

<Statement Block 2>

[Else]

<Statement Block 3>

End If

Here’s an example:

Private Sub Button1_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles Button1.Click

If cboState.Text = "CA" Then

MsgBox "Employee is CA"

ElseIf cboState.Text = "BA" Then

MsgBox "Employee is BA"

ElseIf cboState.Text = "BE" Then

MsgBox "Employee is BE"

End If

End Sub

Page 12: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 12

Prepared By:- Ankit Shah

Select Case

A Select Case statement is used in place of multiple If...Then...ElseIf

statements when youre testing the same condition over and over. Your code is more

efficient and more readable when you use the Select Case construct than multiple

If...Then...ElseIf statements.

Here’s the syntax:

Select Case <Expression>

Case <Expression List 1>

<Statement Block 1>

Case <Expression List 2>

<Statement Block 1>

Case Else

<Statement Block>

End Select

You can use other forms of the Select Case statement. For example, you can use

a comma-delimited list when you need to have the same block of code run for

different cases. You can also use the To operator if you have a range of numbers that

will run the same block of code.

Here’s the example:

Select Case val(txtSalary.Text)

Case 0 To 40000

MsgBox "Tax Rate is 15%"

Case 40001 To 60000

MsgBox "Tax Rate is 24%"

Case 60001 To 80000

MsgBox "Tax Rate is 28%"

Case 80001 To 10000000

MsgBox "Tax Rate is 38%"

End Select

The Choose Function

You use the Choose function to return one of a number of choices based on an index.

Here's the syntax:

Choose(index, choice-1[, choice-2, … [, choice-n]])

If the index value is 1, the first choice is returned, if index equals 2, the second choice

is returned, and so on. Here's an example using Choose. In this case, we have three

employees, Bob, Denise, and Ted, with employee IDs 1, 2, and 3. This code uses an

ID value to assign the corresponding employee name to strEmployName:

TextBox1.Text = Choose(TextBox1.Text, "Bob", "Denise", "Ted")

Page 13: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 13

Prepared By:- Ankit Shah

Looping in VB

The ability to iterate over a series of statements is vital in any programming

language. For example, you need to loop to retrieve items from a list box, and you

need to loop to load items from a database table into a list box. Many other types of looping can occur in your programs. Two types of loop

structures are available in Visual Basic: the Do...Loop and the For...Next

loop. The Do...Loop construct offers many variations and is typically used if you

don’t know how much iteration will be performed. The For...Next loop is typically used when you know the exact number of

iterations to perform on a block of code

Do While

The first form of the Do...Loop you’ll learn about is the Do While

construct.

Do While tests a loop condition each time through the loop, and it keeps

executing while the test expression is a True value.

A Do...Loop is always terminated with a Loop statement. If the condition at

the top of the loop is a True value, the statements between the Do and the Loop

are executed.

It’s possible, with this form of loop, that the statements inside the loop may not

even be executed.

If the condition at the top of the loop evaluates to False, none of the statements

inside of the block are executed.

Here’s the syntax:

Do While <Cond>

<Statement Block>

Loop

The following example is from the Do While command button:

Private Sub Button1_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles Button1.Click

Dim i As Integer

Do While i < 10

System.Console.WriteLine("What?")

i += 1

Loop

End Sub

Page 14: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 14

Prepared By:- Ankit Shah

While . . . End While

The While...End While loop is exactly the same as the Do While loop.

It’s not used too much anymore, but in previous versions of the BASIC language,

it was used quite a lot. Therefore, Visual Basic includes this syntax to maintain

backward compatibility.

This construct is actually not even in the help anymore which means Visual Basic

will probably not support it in a future version.

Here’s the syntax:

While <Cond>

<Statement Block>

End While

The following example is from the While/Wend command button:

Private Sub cmdWhileWend_Click ()

Dim i As Integer

While i < 10

System.Console.WriteLine("What?")

i += 1

End While

End Sub

Loop While

Instead of checking the condition at the top of the loop, as you saw with the Do

While loop, you can also test the condition at the bottom of the loop.

To terminate the loop, you specify Loop While <Condition>. As long as

the condition evaluates to a True value, execution will go back to the top of the

loop and execute the statements again. When you use this format of looping,

you’re guaranteed that the code inside the loop will be executed one time.

Here’s the syntax:

Do

<Statement Block>

Loop While <Cond>

The following example is from the Loop While command button.

Private Sub cmdLoopWhile_Click ()

Dim intNumber As Integer

intNumber = 1

Do

System.Console.WriteLine (intNumber)

intNumber = intNumber + 1

Loop While intNumber < 10

End Sub

Page 15: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 15

Prepared By:- Ankit Shah

Do Until

A Do Until loop is very similar to the Do While loop, except you’re executing

the loop until a condition becomes True. It all depends on what type of logic you

need to use to check the loop condition.

Here’s the syntax:

Do Until <Cond>

<Statement Block>

Loop

The following example is from the Do Until command button.

Private Sub cmdUntil_Click ()

Dim intLoop As Integer

intLoop = 1

Do Until intLoop = 10

System.Console.WriteLine (intLoop)

intLoop = intLoop + 1

Loop

End Sub

Loop Until The Loop Until loop checks the condition at the end of the loop instead of the

beginning of the loop, just like Loop While. The statements inside the loop will

always be performed at least once.

Here’s the syntax:

Do

<Statement Block>

Loop Until <Cond>

The following example is from the Loop Until command button.

Private Sub cmdLoopUntil_Click ()

Dim intLoop As Integer

intLoop = 1

Do

System.Console.WriteLine (intLoop)

intLoop = intLoop + 1

Loop Until intLoop = 10

End Sub

Page 16: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 16

Prepared By:- Ankit Shah

For . . . Next

For...Next loops are generally used when you know the exact number of

iterations that need to be performed. You’ll always use a counter variable that

automatically increments or decrements as you iterate through the loop. Because

you’re using a counter, you’ll always loop from some start value to some end value.

By default, a For...Next loop always increments by one every time through the

loop

Here’s the syntax:

For <Counter> = <Start> To <End> [Step <Inc/Decrement>]

<Statement Block>

Next [<Counter>]

The following example is from the For/Next command button:

Private Sub cmdForNext_Click ()

Dim intLoop As Integer

For intLoop = 1 To 5

System.Console.WriteLine (intLoop)

Next intLoop

End Sub

For . . . Next Step

The Step clause can be added to the For...Next loop to specify the increment

you want to use for the counter variable.

The Step clause is listed after the To variable and is followed by a numeric value

that can be positive or negative. If the number is negative, make sure the start variable

is higher than the end variable.

The following example is from the For/Next Step command button:

Private Sub cmdForStep_Click ()

Dim intLoop As Integer

For intLoop = 10 To 1 Step -1

System.Console.WriteLine (intLoop)

Next intLoop

End Sub

This example is from the For/Next Step 2 command button:

Private Sub cmdForStep2_Click ()

Dim intLoop As Integer

For intLoop = 5 To 50 Step 5

System.Console.WriteLine (intLoop)

Next intLoop

End Sub

Page 17: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 17

Prepared By:- Ankit Shah

A procedure is a set of one or more program statements that can be run or call by

referring to the procedure name.

We can divide the big program into small procedures.

Due to procedure the application is easier to debug and easier to find error.

Reusability of the procedure is the one of the great advantage of it.

Procedures have 2 categories In-built or User-defined procedures.

There are 4 types of Procedures in VB.Net.

In-built

Event-handling procedures are Sub procedures that execute in response to an

event triggered by user action. Like button1_Click.

Property procedures used in object oriented concept.

User-defined

A Sub procedure does not return value.

Function procedures return a value.

Sub Procedure

A sub procedure is nothing more than a small block of program.

It is also known as Sub Routine.

Sub procedure may or may not have arguments. Arguments are not compulsory.

Sub procedure does not return the value.

ByVal is by default argument type.

Syntax:

[accessibility] Sub subname (argumentlist)

Logic…

End Sub

The accessibility can be Public, Protected, Friend, Protected Friend, or Private.

By default accessibility is Public.

Example: Create Sub Procedure when user click on button it will call

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles Button1.Click

Call hai(TextBox1.Text)

End Sub

Sub hai(ByVal str As String)

MsgBox("Hello how r u?" & str)

End Sub

Procedure & Function

Page 18: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 18

Prepared By:- Ankit Shah

Function procedures

A function procedure is similar to sub procedure, but it returns a value to the

calling program.

Function procedure may or may not have arguments.

ByVal is by default argument type.

By default Functions are Public.

Syntax:

[accessibility] Function fuctionname (argumentlist) As Returndatatype

Logic…

[Return value]

End Function

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles Button2.Click

Label3.Text = square(TextBox2.Text)

End Sub

Function square(ByVal no As Integer) As Integer

Return no * no

End Function

Page 19: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 19

Prepared By:- Ankit Shah

In other words, an element's scope is its accessibility in your code.

As we write larger programs, scope will become more important, because we'll be

dividing code into classes, modules, procedures, and so on.

You can make the elements in those programming constructs private, which

means they are tightly restricted in scope.

In VB .NET, where you declare an element determines its scope, and an element can

have scope at one of the following levels:

Block scope—available only within the code block in which it is declared

Procedure scope—available only within the procedure in which it is declared

Module scope—available to all code within the module, class, or structure in

which it is declared

Namespace scope—available to all code in the namespace

Declaring a variable in a procedure gives it procedure scope, and so on. Inside these

levels of scope, you can also specify the scope of an element when you declare it.

Here are the possibilities in VB .NET, which we'll become familiar with throughout

the book:

Public —The Public statement declares elements to be accessible from anywhere

within the same project, from other projects that reference the project, and from an

assembly built from the project. You can use Public only at module, namespace,

or file level. This means you can declare a Public element in a source file or inside

a module, class, or structure, but not within a procedure.

Protected —The Protected statement declares elements to be accessible only

from within the same class, or from a class derived from this class. You can use

Protected only at class level, and only when declaring a member of a class.

Friend —The Friend statement declares elements to be accessible from within the

same project, but not from outside the project. You can use Friend only at module,

namespace, or file level. This means you can declare a Friend element in a source

file or inside a module, class, or structure, but not within a procedure.

Protected Friend —The Protected statement with the Friend keyword declares

elements to be accessible either from derived classes or from within the same

project, or both. You can use Protected Friend only at class level, and only when

declaring a member of a class.

Private —The Private statement declares elements to be accessible only from

within the same module, class, or structure. You can use Private only at module,

namespace, or file level. This means you can declare a Private element in a source

file or inside a module, class, or structure, but not within a procedure.

Understanding Scope

Page 20: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 20

Prepared By:- Ankit Shah

Any software is identified by IDE.

Compare Notepad and Microsoft Word, which one is best for letters and

documents? Your answer is obvious Microsoft Word. But why? Because of the

facilities

Facilities like menu bar, formatting option, toolbar, layout option, chart drawing

options etc. These all are parts of the IDE.

Visual studio.NET provides an environment that’s common to all languages,

which is known as INTEGRATED DEVELOPMENT ENVIRONMENT.

It integrates many different functions such as design, editing, compiling and

debugging within a common environment.

IDE of visual studio.Net as given below image.

Menu Bar o Vary common for any software. Contains options like File, Edit, View,

Project, Build and Help menus.

Context Menus o It contains shortcuts to frequently performed actions.

o To open a context menu, select any object and click the right mouse

button.

o Context menu will open according to object we select.

o The specific list of shortcut available from context menus depends on

the part of the environment where you click the right mouse button.

Component Tray Server

explorer

Solution

explorer

Visual Studio IDE

Page 21: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 21

Prepared By:- Ankit Shah

Toolbars o Provides quick access to commonly used commands like save, undo,

comment, cut, copy, paste run etc.

o By default standard toolbar is appear on visual studio.Net screen.

o We can add other toolbars from view menu or right click on toolbar

itself.

ToolBox (Ctrl + Alt + X) o Provides a set of controls to place on a form.

o We can also set our own toolbox by right click on it.

Solution explorer(Ctrl + Alt + L) o Like window explorer will shows us windows file, same for solution

explorer it will show us each items of our projects files, forms, classes,

namespaces, database etc. that are included in our solution

Property Window (F4) o Lists the properties for the selected controls.

o We can use this window to view and change the design time

properties.

Form Design View ( F7) o We can drag and drop controls in this view of the form.

o We can also see some type of preview of our forms.

Code Editor Window ( F7 )

o Where we can write the coding of the form or class etc.

Immediate, locals and watch window o They are used for debugging our application.

o They are only available when we run our application.

o There are 2 types of watch window, add watch and Quick watch.

Task List( Alt + Ctrl + K) o To view it select view menu - > other windows -> Task list.

o It helps you create and manage a list of programming tasks.

o We can add user Tasks, which are notes about work to be done. A task

can be anything like comments, reminders, URL etc

Page 22: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 22

Prepared By:- Ankit Shah

VB VB.Net

1 VB does not support inheritance,

polymorphism, and operator

overloading features of OOP.

VB.Net support inheritance,

polymorphism, and operator

overloading features of OOP.

2 VB is object based programming

language.

VB.Net is object oriented

programming language.

3 In VB, you cannot create multi

threading application.

In VB.Net you can create

multithreading application.

4 You can handle data in many ways

using DAO, RDO,ADO.

Here, you can handle data with

ADO.Net

5 It has poor error (Un structure)

handling technique.

It supports structure exception

handling technique. It uses Try

()…..Catch()……Finally() blocks.

6 It does not support constructor and

destructor.

It support constructor and destructor.

7 In VB, Set keyword is used to assign

object to variable.

In vb.Net Set keyword is not used.

8 VB by Default, parameter are pass by

reference.

VB.Net by Default, parameter are pass

by values.

9 For color setting it uses QBColor()

and RGB() function.

For color setting, it uses

System.Drawing.Color namespace.

10 It provides poor integration with other

languages. Like C++

It provides, one application can easily

integrate with other application

written in different programming

language.

11 It is platform dependent. It is platform independent.

12 It support the control Array. It does not support the control Array.

13 Co-ordinates for forms and control are

expressed in twips.

Co-ordinates for forms and control are

expressed in pixel

Difference

Page 23: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 23

Prepared By:- Ankit Shah

Error is something that is unexpexted.

Error can stop our program to run.

Errors are drawbacks of the program.

Error is also known as excepton.

Types of Errors

1. Syntax errors

2. Runtime errors

3. Logical errors

Syntax Errors

Syntax errors are those that appear while we write our code.

Also known as design time errors.

Syntax errors are easy to track down in VB.Net because we get a blue line

under the error appears.

Example:

- txtno1.txt = “abc”

- Dim No Integer

Runtime errors

As their name suggests, these errors occur when the program is running.

Runtime errors usually cause your program to crush.

We can fix most runtime errors by rewriting the wrong code.

Example:

- Dividing a number by 0.

- No is integer and if we enter double value.

Logical errors

Logical error effect at runtime only.

Logical errors are difficult to trck down bacause it doesn’t display where the

error is and which type of error is that.

Example:

- For example we want to add two values of TextBox and by mistake we

code for multiply then this type of error is logical error because

program doesn’t disply any error but the ouput of the program is

wrong.

Types Of Errors

Page 24: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 24

Prepared By:- Ankit Shah

As mentioned earlier, there are two ways of handling errors that occur at run time in

VB .NET—with structured and unstructured exception handling. What's an

exception? Exceptions are just runtime errors; in Visual Basic (unlike some other

languages), the terms exception handling and error handling have become inter-

changeable. Exceptions occur when a program is running (as opposed to syntax

errors, which will prevent VB .NET from running your program at all). You can trap

such exceptions and recover from them, rather than letting them bring your program

to an inglorious end.

Unstructured Exception Handling

The old error-handling mechanism in VB6 and before is now called unstructured

exception handling, and it revolves around the On Error Goto statement. You use

this statement to tell VB .NET where to transfer control to in case there's been an

exception, as in this case, where I'm telling Visual Basic to jump to the label

"Handler" if there's been an exception. You create labels in your code with the label

name followed by a colon, and the exception-handling code will follow that label

(note that I've added an Exit Sub statement to make sure the code in the exception

handler is not executed by mistake as part of normal program execution):

Sub Main()

On Error Goto Handler

⋮ Exit Sub

Handler:

⋮ End Sub

Now I can execute some code that may cause an exception, as here, where the code

performs a division by zero, which causes an exception. When the exception occurs,

control will jump to the exception handler, where I'll display a message and then use

the Resume Next statement to transfer control back to the statement immediately

after the statement that caused the exception:

Sub Main()

On Error GoTo err

TextBox3.Text = TextBox1.Text * TextBox2.Text

Exit Sub

err:

MsgBox("Error")

End Sub

When you run this code, you see this message:

Divide by zero error

Exceptions Handling

Page 25: VBsvbitce2010.weebly.com/uploads/8/4/4/5/8445046/vb.net...o 2.0 visual studio 2005 o 3.0 o 3.5 visual studio 2008 o 4.0 visual studio 2010 The .Net framework is a service or platform

P a g e | 25

Prepared By:- Ankit Shah

Structured Exception Handling

Visual Basic also supports structured exception handling. In particular, Visual Basic

uses an enhanced version of the Try…Catch…Finally syntax already supported by

other languages, such as Java. Here's an example that follows our previous example

handling a division by zero exception; I start by creating a Try block—you put the

exception-prone code in the Try section and the exception-handling code in the

Catch section:

Sub Main()

Try

⋮ Catch e As Exception

⋮ End Try

End Sub

Note the syntax of the Catch statement, which catches an Exception object that I'm

naming e. When the code in the Try block causes an exception, I can use the

ex.ToString method to display a message:

Sub Main()

Dim int1 = 0, int2 = 1, int3 As Integer

Try

int3 = int2 / int1

System.Console.WriteLine("The answer is {0}", int3)

Catch ex As Exception

System.Console.WriteLine(ex.ToString)

End Try

End Sub

Here's what you see when you run this code:

System.OverflowException: Exception of type System.OverflowException

was thrown.

at Microsoft.VisualBasic.Helpers.IntegerType.FromObject(Object Value)

at ConsoleHello.Module1.Main() in

C:\vbnet\ConsoleHello\Module1.vb:line 5

Besides using the ex.ToString method, you can also use the ex.message field, which

contains this message:

Exception of type System.OverflowException was thrown.

And now it's time to turn to the Immediate Solutions section to see the details on

creating procedures, setting scope, and handling exceptions.