Вы находитесь на странице: 1из 69

Visual Basic.

NET
Adnan Vallippadan
adnanvp9@gmail.com
Contents
Introduction to .NET Framework ................................................................................................................. 4
VB.NET .......................................................................................................................................................... 4
Console Applications .................................................................................................................................... 4
Web Applications ......................................................................................................................................... 5
Windows Application ................................................................................................................................... 5
Difference between Windows Application and Web Application .............................................................. 5
Keywords ...................................................................................................................................................... 6
Data Types in VB.NET ................................................................................................................................... 6
Numeric Data Types ................................................................................................................................. 6
Non Numeric Data Types ......................................................................................................................... 6
Variables ....................................................................................................................................................... 6
Declaring Variables................................................................................................................................... 7
Assigning values to variables ................................................................................................................... 7
Variables vs Constants ............................................................................................................................. 7
Type Conversion Functions ...................................................................................................................... 7
Operators in VB.NET..................................................................................................................................... 7
Logical Operators in detail ........................................................................................................................... 9
Starting with Console Applications............................................................................................................ 10
Console.Write Method ............................................................................................................................... 11
Console.WriteLine Method ........................................................................................................................ 12
Differences between Console.Write() & Console.WriteLine().................................................................. 12
Console.ReadLine Method ......................................................................................................................... 12
Console.Read Method ................................................................................................................................ 12
Reading Values into Variables from standard input devices .................................................................... 12
Adding Commands in a Program ............................................................................................................... 13
Displaying a Message .................................................................................... Error! Bookmark not defined.
Selection Statements ................................................................................................................................. 14
Iteration Statement.................................................................................................................................... 16
1. While…End While Statements ....................................................................................................... 17
2. Do While…Loop Statements .............................................................................................................. 17
3. Do Until…Loop .................................................................................................................................... 18
4. For…Next Statements ........................................................................................................................ 18
5. For Each…Next Statements ................................................................................................................ 19
6. Do…Loop While Statements .................................................................................................................. 19
7. Do…Loop Until Statements ................................................................................................................ 20
Arrays ...................................................................................................................................................... 21
Object Oriented Programming................................................................................................................... 24
OOP & VB.Net............................................................................................................................................. 27
Introduction to .NET Framework
.NET is a software framework which is designed and developed by Microsoft. The first version
of .Net framework was 1.0 which came in the year 2002. In easy words, it is a virtual machine
for compiling and executing programs written in different languages like C#, VB.Net etc.
It is used to develop Console applications, Form-based applications, Web-based applications,
and Web services. It is used to build applications for Windows, phone, web etc. It provides a lot
of functionalities and also supports industry standards.
.NET Framework supports more than 60 programming languages in which 11 programming
languages are designed and developed by Microsoft.

VB.NET
Visual Basic .NET (VB.NET) is an object-oriented computer programming language implemented
on the .NET Framework.

Console Applications
A console application is a computer program designed to be used via a text-only computer
interface, such as a text terminal, the command line interface of some operating systems (Unix,
DOS, etc.). It doesn’t have any graphical user interface. Console Applications will have character
based interface.

Figure 1
Web Applications
A web-based application is any program that is accessed over a network connection using HTTP,
rather than existing within a device’s memory. Web-based applications often run inside a web
browser. However, web-based applications also may be client-based, where a small part of the
program is downloaded to a user’s desktop, but processing is done over the internet on an
external server.
Web-based applications are also known as web apps.

Windows Application
Windows Application is a user build application that can run on a Windows platform. The
windows application has a graphical user interface that is provided by Windows Forms.
Windows forms provide a variety of controls including Button, TextBox, Radio Button,
CheckBox, and other data and connection controls. You can easily design a web application
using an IDE Microsoft Visual Studio using a variety of languages including C#, Visual Basic, C++,
J# and many more.

Figure 2

Difference between Windows Application and Web Application


1. The first and the foremost difference between Windows and Web Application, Windows
application gets installed on a Windows based operating system whereas the web
application is installed on a web server.
2. Windows application can only be accessed from a system in which it is installed. A web
application can be accessed from any system through internet.
3. You need an Internet Information Services (IIS) server to run the web application.
Windows application can directly be executed on a windows operating system.
4. Windows applications can only be run on a windows platform. Web Application can run
on a variety of platform including Windows, Mac, Linux, Solaris, Android, etc.
5. If designed a 64-bit operating system, a Windows application won’t work on the 32-bit
system. Web application is independent of the type of system.
Keywords
Keywords are a set of predefined words, they have a specific meaning. They are used in all
programming languages.
 Cint
 While
 Int
 String
 Not
 Char
 Write
 Read
 ReadLine
 WriteLine

Data Types in VB.NET


A data type determines the type of the data that is stored in a variable.
Numeric Data Types

Integer Integer Numbers


Long Long Integer Numbers
Single Single Precision Floating Point
Double Double Precision Floating Point
Byte Integer (0 to 255)
SByte Short Byte
Short Short Integer
UInteger Unsigned Integers (+Ve Only)
ULong Unsigned Long Integers (+Ve Only)
UShort Unsigned Short (+Ve Only)

Non Numeric Data Types

String Group of Characters


Date Holds Date
Boolean True or False

Variables
A Variable is an identifier, that denotes a storage space in memory. Every variable has a type
which determines which values are to be stored In it.
While naming a variable we should follow a set of rules as given below
 A variable name can only contain alphabets, digits, and underscores.
 A variable name should not begin with a number or digit.
 A variable name cannot contain a blank space
 Keywords cannot be used as variable names.

Declaring Variables
Variables are required using the Dim statement.
Syntax : Dim Var_Name As Type
We can declare more than one variables using Dim Statement seperated by commas, as given
below.
Dim Var_Name1 As Integer,Var_Name2 As String….
We can assign a value to the variable at the time of declaration itself or by using separate
statements.

Assigning values to variables


We can assign values to the variables at the time of declaration itself or by using a separate
line, using assignment operator.

Dim a As Integer = 13, b As String = "Hello", c As Integer, d As Integer


d = 20
c = 30

Variables vs Constants
Data can be stored as variables & constants.
The content or value of a variable can be change at any time during the program, where as
constants not.

Const PI = 3.14

Type Conversion Functions


Converting one data type to another data type is known as type conversion. Functions used to
convert one data type into another are given below.
CInt Converts into Integer
CLng Converts into Long Integer
CSng Converts into Single data type
CDbl Converts into Double Data Type
CByte Converts into Byte Data Type
CShort Converts into Short Data Type
CDate Converts into Date Data Type
CStr Converts into String Data Type

Operators in VB.NET
An operator is a symbol that is used to perform an operation on one or more expressions,
called operands.
Different types operators are :
 Arithmetic Operators
 Assignment Operators
 Shorthand Assignment Operator
 Concatenation Operator
 Comparison Operator
 Logical Operators
 Miscellaneous Operators

 Arithmetic Operators
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Integer Division (\)
Exponentiation (^)
Mod (%)
 Assignment Operators
A=13
B=C
D=A+B
Sum=0
Fact=1
 Shorthand Assignment Operator
A+=B
A-=B
A*=B
A/=B
A^=B
 Concatenation Operator
In VB.NET we uses two operators for concatination.
‘+’ & ‘&’.
‘+’ is used to concatenate same data types,
‘&’ is used to concatenate different types of data types
 Comparison Operator
Equal to (=)
Not Equal to (<>)
Less than (<)
Greater than (>)
Less than or equal to (<=)
Greater than or equal to (>=)
Is
IsNot
Like
 Logical Operators
Not Operator
And Operator
Or Operator
Xor Operator
AndAlso Operator
OrElse Operator
 Miscellaneous Operators
AddressOf
GetType
TypeOf
If
Function Expression

Logical Operators in detail


All Logical Operators returns boolean value true or false.
1. Not Operator
Returns True if the condition is false.

Condition Output
True False
False True

2. And Operator
AND returns true only if both operands are true and otherwise false.

Condition 1 Condition 2 Output


False False False
True False False
False True False
True True True

3. Or Operator
If any of its arguments are true (or both), it returns true, otherwise it returns false.

Condition 1 Condition 2 Output


False False False
True False True
False True True
True True True

4. Xor Operator
If any of one conditions becomes true, and remaining one becomes false, output
becomes true.

Condition 1 Condition 2 Output


False False False
True False True
False True True
True True False

5. AndAlso Operator

6. OrElse Operator

Starting with Console Applications


To start creating a console application , open visual studio & then choose new project then
choose console applications.

Figure 3
The console code window comprises of modules, where the main module is module1, we can
add a module by clicking on project on menubar and click Add Module.
Figure 4

Figure 5
We can write the program codes inside the sub menu or between sub Main() & End Sub.

Console.Write Method
Writes the text representation of the specified value or values to the standard output stream.
Console.Write("Hiii")
Console.Write("Good Morning")
Console.ReadLine()

Output :
HiiiGood Morning
Console.WriteLine Method
Writes the specified data, followed by the current line terminator, to the standard output
stream.
Console.WriteLine("Hiii")
Console.WriteLine("Good Morning")
Console.ReadLine()

Output :
Hiii
Good Morning

Differences between Console.Write() & Console.WriteLine()


While using Console.Write() Function The curser points on the same line after printing the
variable/parameter.
While using Console.WriteLine() function curser points on the next line.
We can use Console.WriteLine() function to print datas line by line.

Console.ReadLine Method
Reads the next line of characters from the standard input stream.
The ReadLine method reads a line from the standard input stream.
If the standard input device is the keyboard, the ReadLine method blocks until the user presses
the Enter key.
One of the most common uses of the ReadLine method is to pause program execution before
clearing the console and displaying new information to it, or to prompt the user to press the
Enter key before terminating the application.

Console.Read Method
Reads the next character from the standard input stream.

Reading Values into Variables from standard input devices


We can use Console.ReadLine() & Type Conversion functions simultaneously to read values
from keyboard.
Syntax : Var_name=Conversion_function(Console.ReadLine())
Eg : C = CInt(Console.ReadLine())
Which is used to convert one data type into another.
Here it is used with ReadLine() function, to convert the value entered by the user into Integer.
It should be noted that, the variable used with the Conversion function should be same as that
of Conversion Type.

Module Module1
Sub Main()
Dim a As Integer = 13, b As String = "Hello", c As Integer, d As Integer
Console.WriteLine("Enter 2 Numbers")
c = CInt(Console.ReadLine())
d = CInt(Console.ReadLine())
Console.WriteLine(a)
Console.WriteLine(b)
Console.WriteLine("C = " & c & " D = " & d)
Console.ReadLine()
End Sub
End Module

Adding Commands in a Program


We can add commands (Or block certain lines) in VB.NET by two methods, One is adding a
single quotes at the beginning of each line.
Or we can use short keys Ctrl + K & Ctrl + C, after selecting all required lines.
We can uncommend those lines by using short cuts Ctrl + K & Ctrl + U.
'Console.WriteLine("hii")
'Console.ReadLine()

Sample Pgm
Module BasicPgm1
Sub Main()
Dim A As Integer, B As Integer, C As Integer, D As Integer, E As Integer, F As Integer, G As
Integer, K As Integer
Console.WriteLine("Enter two numbers")
A = CInt(Console.ReadLine())
B = CInt(Console.ReadLine())
C=A+B
Console.WriteLine("A + B = " & C)
D=A-B
Console.WriteLine("A - B = " & D)
E=A*B
Console.WriteLine("A * B = " & E)
F=A/B
Console.WriteLine("A / B = " & F)
G=A\B
Console.WriteLine("A \ B = " & G)
If A > B Then
K=A^B
End If
Console.WriteLine("A ^ B = " & K)
Console.ReadLine()
End Sub
End Module

Output :
Enter two numbers
10
3
A + B = 13
A-B=7
A * B = 30
A/B=3
A\B=3
A ^ B = 1000

Selection Statements
Selection statements are statements that changes the flow of a program based on based on a
specific condition met or not.
This expression may be a relational expression or a logical expression which returns a boolean
value (true or false).
Visual Basic supports two types of selection statements
1. If…Else Statement
2. Select…Case Statement
1. If…Else Statement
The If…Else statement is used to test a condition satisfied or not. If it is yes the program control
is transferred to the blocks of code inside the If statement.
Otherwise, the program control is transferred to else block.
If Condition [Then]
[Block of Statements]
ElseIf condition [Then]
[Block of Statements]
Else
[Block of Statements]
End If

Dim a As Integer
Console.WriteLine("Enter a Number")
a = CInt(Console.ReadLine())
Console.WriteLine("Given Number = " & a)
If a > 0 Then
Console.Write("Positive Number")
ElseIf a < 0 Then
Console.Write("Negative Number")
Else
Console.Write("Number = 0")
End If
Console.ReadLine()
2. Select…Case
The Select…Case statements are used to compare value of expression, with different values or
other expressions in the given Case statements. If the case statement matches a specified
expression, the program control is transferred to that statement, as a result, the statements
inside that Case statements are executed.

Select Case testexpression


[Case 1
Statements]
[Case 2
Statements]
………..
[Case n
Statements]
[Case Else
ElseStatements]
End Select

Module Module1
Sub Main()
Dim ch As String
Console.WriteLine("Enter a Character")
ch = Console.ReadLine()
Console.WriteLine("Given Character = " & ch)
Select Case ch
Case "a"
Console.WriteLine("Vowel")
Case "e"
Console.WriteLine("Vowel")
Case "i"
Console.WriteLine("Vowel")
Case "o"
Console.WriteLine("Vowel")
Case "u"
Console.WriteLine("Vowel")
Case Else
Console.WriteLine("Not a Vowel")
End Select
Console.ReadLine()
End Sub
End Module
Module Module1
Sub Main()
Dim ch As String
Console.WriteLine("Enter a Character")
ch = Console.ReadLine()
Console.WriteLine("Given Character = " & ch)
Select Case ch
Case "a", "e", "i", "o", "u"
Console.WriteLine("Vowel")
Case Else
Console.WriteLine("Not a Vowel")
End Select
Console.ReadLine()
End Sub
End Module

Module Module1
Sub Main()
Dim i As Integer
Console.WriteLine("Enter a Character")
i = CInt(Console.ReadLine())
Select Case i
Case 1 To 10
Console.WriteLine("Number is between 1 & 10")
Case 11 To 20
Console.WriteLine("Number is between 11 & 20")
Case 30, 40, 50
Console.WriteLine("Number = 30 or 40 or 50")
Case Else
Console.WriteLine("Given Number = " & i)
End Select
Console.ReadLine()
End Sub
End Module

Iteration Statement
An Iteration statement executes a statement or set of statements repeatedly based on a
certain conditions. Iteration statements are also called loop statements.
Visual Basic 2010 Supports seven basic types of loop statements.
1. Entry Controlled Loops
a. The While…End While Statements
b. The Do While…Loop Statements
c. Do Until…Loop Statements
d. The For…Next Statements
e. The For Each…Statements
2. Exit Controlled Loops
a. Do…Loop While
b. Do…Loop Until
All types of loop contains 3 basic elements
 Initialization Expression
 Update Expression
 Body of loop
1. While…End While Statements
The While…End While Statements continues to execute a set of statements as long as the given
condition is true. The while statement always checks the condition before executing the
statements within the loop, therefore it is called entry controlled loop. When the control
reaches the End While statement , the control is passed back to the While statement. If the
condition is becomes true, the statements within the loop are executed again & again;
otherwise , the loop exits.
The syntax of While statement is as follows:
While condition
[Statements]
End While
We can also terminate a while statements any time with an Exit While Statement.

Module Module1
Sub Main()
Dim i As Integer
While i <= 10
Console.WriteLine(i)
i=i+1
End While
Console.ReadLine()
End Sub
End Module

2. Do While…Loop Statements
The Do While…Loop statements is also used to execute a group of statements repeatedly.
The Do While…Loop statement executes a group of statements repeatedly as long as the
condition evaluates true. The Do While statement always checks the condition before executing
the statements within the loop, therefore it is called entry controlled loop.
When condition becomes false the loop terminates automatically.

The syntax for Do…Loop statements as follows:


Do while condition
[Statements]
Loop

Module Module1
Sub Main()
Dim i As Integer = 1
Do While i <= 10
Console.WriteLine(i)
i += 1
Loop
Console.ReadLine()
End Sub
End Module

3. Do Until…Loop
The Do Until…Loop statements is also used to execute a group of statements repeatedly.
The Do Until…Loop statement executes a group of statements repeatedly as long as the
condition evaluates false. The Do While statement always checks the condition before
executing the statements within the loop, therefore it is called entry controlled loop.
When condition becomes true the loop terminates automatically.

Do while condition
[Statements]
Loop

Module Module1
Sub Main()
Dim i As Integer
Do Until i > 10
Console.WriteLine(i)
i=i+1
Loop
Console.ReadLine()
End Sub
End Module
4. For…Next Statements
The For…Next Statement is used when we have to execute a group of statements repeatedly
for a specific number of times. The For…Next loop needs an index variable which counts the
no.of iterations. The counter variable automaticaly increment by one when looping through the
cycle.
Synatax :
For Variable = Start_Index To End_Index
[Statements]
[Exit For]
[Statements]
Next

Module Module1
Sub Main()
Dim i As Integer
For i = 1 To 10
Console.WriteLine(i)
Next
Console.ReadLine()
End Sub
End Module

5. For Each…Next Statements


The For Each…Next Statement iterates through all the items in a list, which may be an array or a
collection of objects.

Syntax :
For Each var_name As Type In Group
[Statements]
[Exit For]
Next

Module Module1
Sub Main()
Dim arr() As Integer = {1, 2, 3, 4, 5, 6}
For Each i As Integer In arr
Console.WriteLine(i)
Next
Console.ReadLine()
End Sub
End Module

6. Do…Loop While Statements


The Do…Loop While statements is also used to execute a group of statements repeatedly.
The Do…Loop While statement executes a group of statements repeatedly as long as the
condition evaluates true. The Do While statement always checks the condition after executing
the statements within the loop, therefore it is called exit controlled loop. When condition
becomes false the loop terminates automatically. If the test expression is false, loop body will
be executed once.
Do
[Statements]
Loop while condition

Module Module1
Sub Main()
Dim i As Integer
Do
Console.WriteLine(i)
i=i+1
Loop While i <= 20
Console.ReadLine()
End Sub
End Module

7. Do…Loop Until Statements


The Do…Loop Until statements is also used to execute a group of statements repeatedly.
The Do…Loop Until statement executes a group of statements repeatedly as long as the
condition evaluates false. The Do While statement always checks the condition after executing
the statements within the loop, therefore it is called exit controlled loop. When condition
becomes true the loop terminates automatically. If the test expression is true, loop body will be
executed once.

Do
[Statements]
Loop Until condition

Module Module1
Sub Main()
Dim i As Integer
Do
Console.WriteLine(i)
i=i+1
Loop Until i = 20
Console.ReadLine()
End Sub
End Module

Sample Pgm
Program to find largest among two numbers
Module Module1
Sub Main()
Dim a As Integer, b As Integer
Console.WriteLine("Enter Two Numbers :")
a = CInt(Console.ReadLine())
b = CInt(Console.ReadLine())
If a > b Then
Console.WriteLine("Greater Number = " & a)
Else
Console.WriteLine("Greater Number = " & b)
End If
Console.ReadLine()
End Sub
End Module

Sample Pgm
Program to find largest among three numbers
Module Module1
Sub Main()
Dim a As Integer, b As Integer, c As Integer
Console.WriteLine("Enter 3 numbers")
a = CInt(Console.ReadLine())
b = CInt(Console.ReadLine())
c = CInt(Console.ReadLine())
If a > b Then
If a > c Then
Console.WriteLine("Largest Number = " & a)
Else
Console.WriteLine("Largest Number = " & c)
End If
Else
If b > c Then
Console.WriteLine("Largest Number = " & b)
Else
Console.WriteLine("Largest Number = " & c)
End If
End If
Console.ReadLine()
End Sub
End Module

Arrays
An array stores a fixed-size sequential collection of elements of the same type. An array as a
collection of variables of the same type. It is used to store a collection of data.
All arrays consist of continuous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
To declare an array in VB.Net, you use the Dim statement. Array elements can be accessed
using array index or bounce. While declaring an array, we uses its highest bounce (index) as
parameter. When we declare an array with bounce 4, actually it stores 5 elements , bcoz lowest
bounce starts from 0.

Dim intData(30) ' an array of 31 elements


Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array
An array’s index is called bounce, it starts from 0 & ends with the size given with declaration.
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _
"Shivangi", "Ashwitha", "Somnath"}
The elements in an array can be stored and accessed by using the index of the array.
We can display each elements in an array using For Each…Next statements.
Sample Pgm
Program to demonstrate declaration & initialization of array.
Module Module1
Sub Main()
Dim arr(5) As Integer, i As Integer
Console.WriteLine("Enter Elements")
For i = 0 To 5
arr(i) = CInt(Console.ReadLine())
Next
Console.WriteLine("Elements are")
For Each vl As Integer In arr
Console.WriteLine(vl)
Next
Console.ReadLine()
End Sub
End Module
Dynamic Arrays
Dynamic arrays are the arrays whose size varies at runtime. This type of array is used to store a
list of values that can be changed during the execution of the program. We can declare a
dynamic array without specifying size in the parenthesis, by using the Dim statement.
To specify the size of array at run time, we need to use ReDim statement.
ReDim Preserve array_name(size)
The preserve keyword is used to preserve the data in an existing array when we change the size
of the array.

Sample Pgm
Program to demonstrate dynamic arrays.
Module Module1
Sub Main()
Dim arr() As Integer, i As Integer
ReDim arr(3)
Console.WriteLine("Enter Elements")
For i = 0 To 3
arr(i) = CInt(Console.ReadLine())
Next
Console.WriteLine("Elements are")
For Each vl As Integer In arr
Console.WriteLine(vl)
Next
ReDim arr(6)
Console.WriteLine("Enter Elements")
For i = 4 To 6
arr(i) = CInt(Console.ReadLine())
Next
Console.WriteLine("Elements are")
For Each vl As Integer In arr
Console.WriteLine(vl)
Next
Console.ReadLine()
End Sub
End Module
Sample Pgm
Program to demonstrate dynamic arrays using preserve keyword.
Module Module1
Sub Main()
Dim arr() As Integer, i As Integer
ReDim arr(3)
Console.WriteLine("Enter Elements")
For i = 0 To 3
arr(i) = CInt(Console.ReadLine())
Next
Console.WriteLine("Elements are")
For Each vl As Integer In arr
Console.WriteLine(vl)
Next
ReDim Preserve arr(6)
Console.WriteLine("Enter Elements")
For i = 4 To 6
arr(i) = CInt(Console.ReadLine())
Next
Console.WriteLine("Elements are")
For Each vl As Integer In arr
Console.WriteLine(vl)
Next
Console.ReadLine()
End Sub
End Module

Object Oriented Programming


The fundamental idea behind object oriented programming is to combine into a single unit both
data and related functions together. Such a unit is called as an Object.
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects.
It simplifies the software development and maintenance by providing some concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Object
Any entity that has state and behavior is known
as an object. It can be physical or logical.
An Object can be defined as an instance of a
class. Both data and function that operate on
data are bundled as a single unit, called as object.
Anything that we see around us can be treated as
an object and all these objects have properties
(also called member/data/state) and
behaviour (also called
methods/member functions).

Class
Simply a class is called collection of
objects. An object is defined via its
class which determines everything
about an object. A class is a
prototype/blue print that defines the
specification common to all objects of
a particular type. This specification
contains the details of the data and
functions that act upon the data.
Objects of the class are called
individual instances of the class and
any number of objects can be created based on a class.

Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As the
name suggests Inheritance is the process of forming a new class from an existing class that is
class called as base class, new class is formed called as derived class.
This is a very important concept of object-oriented programming since this feature helps to
reduce the code size.
Polymorphism
'Poly' means many. 'Morph' means shapes. So polymorphism can be defined as the ability to
express different forms. This is demonstrated in Figure . Here the same command "Now Speak"
is issued to all objects, but each object
responds differently to the same command.

In object-oriented programming, polymorphism refers to the ability of a programming language


to process objects differently depending on their data type or class. More specifically, it is the
ability to redefine methods for derived classes.
For example, given a base class Shape, polymorphism enables the programmer to define
different area methods for any number of derived classes such as circle, rectangle and triangle.
No matter what shape an object has, applying the area method to it will return the correct
results.

Abstraction
Data abstraction refers to, providing only essential information to the outside world and hiding
their background details, i.e., to represent the needed information in program without
presenting the details.
Let us take a real life example of a television which we can turn on and off, change the channel,
adjust the volume, and add external components such as speakers, VCRs, and DVD players, but
we do not know about its internal details, that is, we do not know how it receives signals over
the air or through a cable, how it translates them, and finally displays them on the screen.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
All C++ programs are composed of two fundamental elements, functions and data.
Encapsulation is an OOP concept that binds together the data and functions that manipulate
the data, and keeps both data and function safe from outside interference and misuse.
The best way to understand encapsulation is to look at the example of a medical capsule,
where the drug is always safe inside the capsule. Similarly, through encapsulation the methods
and variables of a class are well hidden and safe.

OOP & VB.Net


The concepts of an Object Oriented Programming can be used in VB.Net .
Classes & Objects
A Class is a primary building block of an object oriented programming. We can use classes to
encapsulate variables & methods into a single unit. The declaration of a class starts with
keyword Class followed by class name.
Syntax For creation of class is shown below :
<access_modifiers> Class <class_name>
Class Variables
Class Methods
End Class
In order to access variables and methods in a class, we needs to create an object of the same
class.
Syntax for Object creation is given below :
<access-modifiers> <object_name> As <class_name> ‘Object Declaration
<object_name> = New Class_Name(Parameters) ‘Object Initialisation
There are some importanat concepts related to class
 Access Modifiers
 Methods
 Constructors & Destructors
 Partial Classes
 Shared Methods
 Extension Methods
Access Modifiers
Access modifiers are keywordsnused to specify the accessibility of a member or type. It protect
an object of a class from outside interference. The access modifiers protects an object by
defining a certain scope to access iits data & methods in a restricted manner. We can declare a
class & its method with access modifiers.
Different types access modifiers are
1. Public
Gives Unrestricted access to members both inside & outside a class.
Syntax :
Public Class Class_Name
2. Protected
Gives protected access to members . You can access protected members either from the
class in which they are declared or a derived class from where it is declared.
Syntax :
Protected Class Class_Name
3. Friend
Gives access to members that are in the same assembly. If a member with the friend access
modifier is accessed outside the assembly in which it has been defined, an error is
generated.
Syntax :
Friend A As String
4. Protected Friend
Gives access to members that are either from the derived classes or within the same
assembly or both.
Syntax :
Protected Friend A As String
5. Private
Gives access to members that are within the body of the class in which they are declared.
Private A As Integer
Methods
In VB methods is a block of statements that contains a series of statements to perform an
action. Methods are declared in a class by specifying the access level, the return value, name of
method and method parameters.
A method that does not return a value is called a sub procedure, and the method that returns a
value is called function.
Sub Procedure
A sub procedure is a series of statements enclosed by Sub and End Sub Statements. A sub
procedure can’t return values.
Sub Sub_Procedure_Name(Parameters)
Statements
End Sub
To execute this sub procedure , we must call this sub procedure using their name &
parameters, as shown below :
Sub_Procedure_Name(Parameters)

Sub main()
displaymsg()
Console.ReadLine()
End Sub
Sub displaymsg()
Console.WriteLine(“Welcome”)
End Sub
The parameter mentioned here means that, the values or variables that are passed to sub
procedure or a function, they are also called arguments.
We can pass values into sub procedure by 2 ways.
1. Pass By Value
In the pass by value method, a separate copy of variable is passed to the sub procedure. If
we makes any changes to the value passed into sub procedure, it willnot affect the value in
the original copy. VB uses ByVal Keyword when a value is passed to a sub procedure.
Sub Display(ByVal str As String)
Console.writeLine(str)
Console.Readline()
End Sub

Module Module3
Sub Main()
Dim C As Integer
Console.WriteLine("Enter a Number")
C = CInt(Console.ReadLine())
display(C)
Console.WriteLine("C = " & C & " From Sub Main Procedure")
Console.ReadLine()
End Sub
Sub display(ByVal C As Integer)
C = C + 20
Console.WriteLine("C = " & C & " From Sub Procedure")
End Sub
End Module

OutPut :
Enter a Number
70
C = 90 From Sub Procedure
C = 70 From Main Procedure
2. Pass By Reference
When you pass an argument by Pass by reference method, the location of the variable is
passed to the sub procedure. This implies that we have direct access to that variable. That
means , Changing the value of an argument in sub procedure also changes the value in its
original copy.
Sub Display(ByRef str As String)
Console.writeLine(str)
Console.Readline()
End Sub

Module Module3
Sub Main()
Dim C As Integer
Console.WriteLine("Enter a Number")
C = CInt(Console.ReadLine())
display(C)
Console.WriteLine("C = " & C & " From Sub Main Procedure")
Console.ReadLine()
End Sub
Sub display(ByRef C As Integer)
C = C + 20
Console.WriteLine("C = " & C & " From Sub Procedure")
End Sub
End Module
OutPut :
Enter a Number
40
C = 60 From Sub Procedure
C = 60 From Main Procedure

Functions
Functions are similar to sub procedures, except the difference is that a function can return
values. The syntax for creation of function is shown below :
Function Function_name(Parameters) As Return_Type
Statements
Return Statement
End Function
A function can be created using the keyword Function. Followed by Function_name. The
parameters here refers to the list of values which are passed to the function. The
values/Variables can be passed to function using PassBy value or PassBy Methods.
Function has a return statement which denotes which type & value is returned after executing
the function.
Module Module2
Function addition(ByVal a As Integer, ByVal b As Integer) As Integer
Dim sum As Integer
sum = a + b
Return sum
End Function
Sub Main()
Dim sum As Integer
sum = addition(15, 25)
Console.WriteLine("Sum = " & sum)
Console.ReadLine()
End Sub
End Module

Constructors & Destructors


Constructors & destructors are special types of methods. A constructor is a method that is
called when an object of a class is created. It is used to initialize all class members. In VB the
New keyword is used to create constructors.
The main features of a constructor are :
 It is a sub procedure declared with New keyword
 It has same name as that of class itself
 It do not have a return type
 It is not mandatory to define a constructor
We can create an object of a class by using Dim statement.
Dim Object_Name As Class_Name
Example :
Dim Obj As Students
A destructor is a method that is called when an object is finally destroyed. It is used to destroy
values assigned to the class members, when the object is not required any more. You cannot
call a destructor in your application ; it is invoked automatically. Visual basic provides a garbage
collection mechanism that is executed when the runtime environment finds it necessary or
when an object is not destroyed until its reference count drops to 0. Similar to constructor , a
destructor also has the same name of the class in which it is defined.
A constructor can be defined with & without parameters. While passing parameters the PassBy
Value & PassBy Reference mechanisms are also used.

Module Module1
Public Class students
Dim rgn As Integer, name As String
Public Sub New() ‘Constructor without parameters
Console.WriteLine("Enter Reg Num & Name")
rgn = CInt(Console.ReadLine())
name = Console.ReadLine()
End Sub
Public Sub New(ByVal n As Integer, ByVal nm As String)
‘Constructor with parameter
rgn = n
name = nm
End Sub
Sub display()
Console.WriteLine("Register Number : " & rgn)
Console.WriteLine("Name : " & name)
End Sub
End Class
Sub Main()
Dim obj1 As students = New students()
Dim obj2 As students = New students(2, "Abhi")
Dim obj3 As students = New students(3, "Arun")
obj1.display()
obj2.display()
obj3.display()
Console.ReadLine()
End Sub
End Module

When can create an array of objects, which means we can create any no.of objects of a same
class by using Arrays.

Module Module1
Class student
Private regno As Integer
Private name As String
Private phno As Long
Private marks As Double
Public Sub New()
Console.WriteLine(Constants.vbLf & "Enter Registration
Number")
regno = CInt(Console.ReadLine())
Console.WriteLine("Enter Name")
name = Console.ReadLine()
Console.WriteLine("Enter Phone Number" & Constants.vbLf)
phno = CLng(Console.ReadLine())
Console.WriteLine("Enter Marks")
marks = CDbl(Console.ReadLine())
End Sub
Public Sub display()
Console.WriteLine("Registration Number : " & regno)
Console.WriteLine("Name : " & name)
Console.WriteLine("Phone Number : " & phno)
Console.WriteLine("Marks obtained : " & marks)
End Sub
End Class
Sub Main()
Dim obj(3) As student
For i = 0 To 3
Console.WriteLine("Enter datas of student " & i + 1)
obj(i) = New student()
Next
For i = 0 To 3
Console.WriteLine("Datas of student " & i + 1)
obj(i).display()
Next
Console.ReadLine()
End Sub
End Module

Partial Classes
In VB , a partial class is the class that enables you to specify the definition of a class in two or
more source files. All the source file contain a section of the class definition. The definitions in
the different source files are combined when the application is executed. We can divide a class
into 2 or more partial classes each stored in separate files , so that we can work on each partial
class seperately. We can declare a partial class by using the Partial keyword. The partial
keyword indicates that all the parts of the class must be available at compile time to generate
the final class.
Module Module1
Partial Public Class sample 'Partial Class Definition 1
Public x As Integer
Public y As Integer
Public Sub New(ByVal p As Integer, ByVal q As Integer)
x = p
y = q
End Sub
End Class
Partial Public Class sample 'Partial Class Definition 2
Public Sub display()
Console.WriteLine("a = " & x)
Console.WriteLine("b = " & y)
End Sub
End Class
Sub Main()
Dim obj As sample = New sample(29, 25)
obj.display()
Console.ReadLine()
End Sub
End Module

Shared Methods
A shared method refers a method that is directly accessed without creating an instance of the
class in which it is declared. We can use the class name and the dot operator (.) to access a
shared method outside the class.
Module Module1
Public Class MathAddition
Public Shared Sub addition(ByVal a As Integer, ByVal b As
Integer)
Console.WriteLine("Sum = " & a + b)
End Sub
End Class
Sub Main()
MathAddition.addition(10, 20)
MathAddition.addition(15, 25)
Console.ReadLine()
End Sub
End Module

Extensions Methods
An extension method is one of the new features in Visual Basic 2010. It is a technique used to
extend a class from that class. The behaviour of extension methods is similar to that of shared
methods. An extension methods can be either a function or a sub procedure.
To define a method as an extension method , you must mark the method with extension
attribute, <Extension()> , which belongs to the System.Runtime.CompilerServices namespace.
Imports System.Runtime.CompilerServices
Module Module1
<Extension()>
Public Sub display()
Console.WriteLine("Welcome to my program")
End Sub
End Module
In the above example, we created a sub procedure display(), which marked as <Extension()>. To
use an extension attribute we must import System.Runtime.CompilerServices namespace.
Extension methods can be declared only within modules. The module, in which an extension
method defined, is not the same module as one in which it is called.
Imports ConsoleApplication39.Module1
Module Module2
Sub Main()
display("Welcome to my program")
Console.ReadLine()
End Sub
End Module
For calling this extension method, we added a new module Module2, & then import the
previous module as shown below.
Imports Project_Name.Module_Name

Encapsulation
Encapsulation is the process of hiding the irrelevent information and showing only the relevent
information to a user. It is away to organize data and methods to a single unit ; thereby,
preventing the data from being modified by unauthorized users. Encapsulation is implemented
through access modifiers. Access modifiers help to improve the this feature by defining a scope
to access data and methods in a restricted manner.
Consequently, you can describe encapsulation as the ability of an object to hide its internal data
and methods and to make only the intended parts programmatically accessible.
In terms of OOP, encapsulation is the process of wrapping data and members in a class. Only
specific methods or properties can access the private members of a class. In other words,
encapsulation is an approach to hide the internal state and behaviour of a class or an object
from unauthorized access. It restricts the external users sharing and manipulating data.
The advantages of encapsulation are as follows:
 Data hiding through the use of the private access modifiers
 Increasing the maintainability of the code
 Preventing data corruption
 Wrapping up of data members & member functions
Module Module1
Class class1
Private x As Integer = 20
Public y As Integer = 30
Protected z As Integer = 90
Public Sub display()
Console.WriteLine("X = " & x)
Console.WriteLine("Y = " & y)
Console.WriteLine("Z = " & z)
End Sub
End Class
Sub Main()
Dim obj As class1 = New class1()
Console.WriteLine("Y = " & obj.y)
obj.display()
Console.ReadLine()
End Sub
End Module
All the class members are accessible except the private members . Private members are only
accessible in the class in which they are declared.
Protected members are accessible from either the class in ehich they are declared or a class
derived from the class in which they are declared.
Inheritance
inheritance is defined as the property through which a child class obtains all features defined in
its parent class. A parent class is the higher level in the class hierarchy as compared to the child
class. Inheritance represents a kind of relationship between two classes.
For Eg: consider the parrot as a child class, it obtains all features from the parent class, the bird
class.
When a class inherits the properties of another class, the class inheriting the properties is called
a derived class and the class that allows inheritance of its properties is called a base class.
Inheritance in OOP is of 4 Types :
1. Single inheritance :
Contains one base class & one derived class

2. Hierarchical inheritance :
Contains one base class and multiple derived classes of the same base class

3. Multilevel inheritance :
Contains a class derived from another derived class

4. Multiple Inheritance :
Contains several base classes and a derived class

A derived class inherits all the non-private data of its base class. It also inherits the behaviour of
the base class.
Defining a derived Class
We uses keyword Inherits to inherit properties from a Base Class.
Accessing Members of the Base Class
When a class is derived from a base class, the members of the base class becomes members of
the derived class. We can access those variable using object of derived class & dot operator (.).
Module Module1
Public Class classA 'Base Class
Public a As Integer = 10
Protected b As Integer = 20
Private c As Integer = 30
Public Sub display()
Console.WriteLine("Hii Welcome")
Console.WriteLine("Private Variable : " & c)
Console.WriteLine("Protected Variable : " & b)
End Sub
End Class
Public Class classB 'Derived Class
Inherits classA 'Inherited from ClassA
Public Sub show()
Console.WriteLine("Protected Variable : " & b)
End Sub
End Class
Sub main()
Dim obj2 As classB = New classB()
Console.WriteLine("Accessing Members of Base Class From
Derived Class")
obj2.display()
Console.WriteLine("Public Variable : " & obj2.a)
obj2.show()
Console.ReadLine()
End Sub
End Module
Abstract Classes
Abstract classes are that contains only the declaration of a method; whereas, the method is
defined in the class derived from the abstract class. In other words abstract classes are similar
to the base classes except that the methods are declared inside the abstract classes, known as
abstract methods, they do not have method bodies. If you have created a base class and want
to ensure that no object of the base class is created later, we can make the base class as
abstract. The MustInherit keyword in a class indicates that the class cannot be instantiated and
is an abstract class. The basic purpose of abstract class is to provide a common definition of the
base class that can be shared by multiple derived classes.
Characteristics of an abstract class are given below:
 We cannot instantiate an abstract class directly. This implies that you cannot create an
object of the abstract class. To use members of an abstract class, you need to define a
non-abstract class that inherits the abstract class. After you have defined the non
abstract classes, you can access the members of the abstract class using the object of
the non abstract classes.
 An abstract class can contain abstract as well as non-abstract members
 You must declare at least one abstract method in a abstract class
 An abstract class is always public
Module Module1
Public MustInherit Class areaofshape
Public a As Double = 12
Public MustOverride Function area() As Double
End Class
Public Class circle
Inherits areaofshape
Public Overrides Function area() As Double
Dim ar As Double
ar = 3.14 * a * a
Return ar
End Function
End Class
Public Class square
Inherits areaofshape
Public Overrides Function area() As Double
Dim ar As Double
ar = a * a
Return ar
End Function
End Class
Sub Main()
Dim obj1, obj2 As areaofshape
obj1 = New circle()
obj2 = New square()
Console.WriteLine("Area of Circle = " & obj1.area())
Console.WriteLine("Area of square = " & obj2.area())
Console.ReadLine()
End Sub
End Module

Sealed Classes
A sealed class implies that the class cannot be used as a base class. You can declare a class as
sealed, if you want to prevent other users to derive a class from that class. Once you have
declared as sealed, no other class can inherit that class. The NotInheritable keyword is used to
indicate that a class cannot be inherited. When we apply the NotInheritable keyword as a
modifier to a class, it will become final.
Module module1
NotInheritable Class sealedclass
Public Sub display()
Console.WriteLine("Hello Everyone")
End Sub
End Class
Sub Main()
Dim obj As sealedclass = New sealedclass()
obj.display()
Console.ReadLine()
End Sub
End Module
Polymorphism
polymorphism means one name many forms. Using this feature of polymorphism, you can use
one method in many ways based on your requirements.
For example, you can write a method to calculate the area of a geometrical figure and use the
same method to calculate area of circle, triangle, or rectangle using different values & types of
parameters.
Polymorphism is of two types
1. Compile Time Polymorphism
2. Run Time Polymorphism
Compile Time Polymorphism
When a compiler compiles compiles a program, the compiler has the information about the
method arguments. Accordingly, the compiler finds the appropriate method to the respective
object at the compile time itself. This process is called compile time polymorphism or early
binding. We can implement compile time polymorphism through overloaded methods and
operators. The arguments passed to overloaded methods are matched interms of number,
type, and order; and then the overloaded methods are invoked.
Compile time polymorphism can be implemented In two ways
1. Method Overloading
2. Operator Overloading
Method Overloading
Method overloading is a concept in which a method in which a method behaves according to
the number and types of parameters passed to it. It allows you to define multiple methods with
the same name but with different signatures. When you call overloaded methods, the compilor
automatically determines which method should be used according to the signature specified in
the method call.
Module Module1
Public Class shape
Public Sub area(ByVal side As Integer)
Dim area As Integer = side * side
Console.WriteLine("Area of Square : " & area)
End Sub
Public Sub area(ByVal length As Integer, ByVal breadth As Integer)
Dim area As Integer = length * breadth
Console.WriteLine("Area of rectangle : " & area)
End Sub
Public Sub area(ByVal rad As Double)
Dim area As Double = 3.14 * rad * rad
Console.WriteLine("Area of Circle : " & area)
End Sub
End Class
Sub Main()
Dim obj As shape = New shape()
obj.area(25)
obj.area(10, 20)
obj.area(10.0)
Console.ReadLine()
End Sub
End Module

Creating a structure
A structure in VB is a user defined value type. It is used to store values of different data types.
Similar to class, it can contain constructors, fields, methods and nested types. We can use the
structure statement to create a structure. All elements of a structure are private by default. In
VB major difference between structure & class is that a structure does not support inheritance.
The syntax of a structure declaration is given below:
<attributelist> <accessmodifier> Structure Structure_Name
[Implements Interfacenames]
Data Member Declarations
[method declarations]
End Structure

Module module1
Public Structure sample
Public x As Integer
Public y As Integer
Public z As Integer
End Structure
Sub Main()
Dim v1 As sample
v1.x = 10
v1.y = 20
v1.z = 30
Console.WriteLine("X = {0} Y = {1} Z = {2}", v1.x, v1.y, v1.z)
Dim v2 As sample = New sample()
Console.WriteLine("X = {0} Y = {1} Z = {2}", v2.x, v2.y, v2.z)
Console.ReadLine()
End Sub
End Module

Properties
A property provides you a way to expose an internal element (Private Variable) of a class in a
simple and intuitive manner. We can create a property by defining an externally available
name. The Get & Set property procedures are used to implement the property. The Get
property procedure is used to return the property value and the Set property procedure is used
to assign a new value to the property.

Module Module1
Public Class EmployeeDetail
Private empname As String
Public Property Name() As String
Get
Return empname
End Get
Set(ByVal value As String)
empname = value
End Set
End Property
End Class
Sub Main()
Dim emp1 As EmployeeDetail = New EmployeeDetail()
emp1.Name = "Neelima Agarwal"
Console.WriteLine("Employee Name = {0}", emp1.Name)
Console.ReadLine()
End Sub
End Module

Creating Anonymous type for Read-only properties


While creating properties for your application you might need to create a few read only
properties as well. We can encapsulate these Read-Only properties into a single unit through
anonymous types. Using anonymous types , you need to Explicitly define a type to encapsulate
the Read-Only properties of an object as the type name is generated by the compiler.
The declaration of an instance of an anonymous type starts with the New keyword , followed by
With keyword. The statement, New With {.Name=”Key Board” , .Price=200} , creates an
anonymous type instance with a member named Name.
An anonymous type provides you an easy way to encapsulate a set of read-only properties into
a single object without defining a new type.
Module Module1
Sub Main()
Dim Product = New With {.Name = "Key Board", .Price = 250,
.Brand = "Dell"}
Console.WriteLine("Product Details")
Console.WriteLine("Name : {0}", Product.Name)
Console.WriteLine("Price : {0}", Product.Price)
Console.WriteLine("Brand : {0}", Product.Brand)
Console.ReadLine()
End Sub
End Module

Using Auto – Implemented Properties


Auto – implemented properties allow you to automatically create a property without specifying
Get & Set. After you have created an auto-implemented property, the visual basic compiler
automatically creates the Get & Set procedures for the property in addition to a private field
that stores the property variable.
In VB you can create an auto-implemented property that includes a default value in a single line
of code, as shown below:
Property Name As String = "Neelima"

Module Module1
Property Name As String = "Neelima"
Property Age As Integer = 26
Sub Main()
Console.WriteLine(Name)
Console.WriteLine(Age)
Console.ReadLine()
End Sub
End Module

Using Interfaces
An interface is a collection of abstract data members and member functions. Interfaces in visual
basic are introduced to provide the feature of multiple inheritance to classes. The method
defined in an interface do not have their implementation. They only specify the number & types
of parameters they will take and the type of values they will return. An interface is always
implemented by a class. In VB an interface is equivalent to abstract base class. You cannot
instantiate an object through an interface. But you can offer a set of functionalities that is
common to several different classes.
Defining an interface
Similar to defining a class, we can define an interface. The difference is that a class is defined
with the Class keyword and an interface is defined with Interface keyword. The syntax to define
an interface is shown below
Interface InterfaceName
'Abstract Method Declarations in Interface Body
End Interface
You can use the Implements keyword to implement an interface.

Windows Forms Applications


A form is a graphical user interface (GUI) for building windows client applications that use
common language run time (CLR) its execution. A windows form application allows you to
design multiple forms to perform various tasks by using different types of controls. In addition,
a windows forms application enables to create smart client applications by including features,
such as tabbed navigation, ordering of tabs, and handling mouse events. In Visual Basic 2010,
the support for windows forms is provided in System.Windows.Forms namespace.

A Windows forms application is one that runs on the desktop computer. A Windows forms
application will normally have a collection of controls such as labels, textboxes, list boxes, etc.
Below is an example of a simple Windows form application. It shows a simple Login screen,
which is accessible by the user. The user will enter the required credentials and then will click
the Login button to proceed.

Opening an Windows Form Application


New Project  Windows Forms Application

1. Editor Window or
1 Main Window 2 3
2. Solution Explorer
Window
3. Properties Window
Editor Window or Main Window: Here, you will work with forms and code editing. You can
notice the layout of form which is now blank. You will double click the form then it will open the
code for that.

Solution Explorer Window: It is used to navigate between all items in solution. For example, if
you will select a file form this window then particular information will be display in the property
window. (Right Side, Ctrl + R)

Properties Window: This window is used to change the different properties of the selected
item in the Solution Explorer. Also, you can change the properties of components or controls
that you will add to the forms. (Right Side, F4)

You can also reset the window layout by setting it to default. To set the default layout, go to
Window -> Reset Window Layout in Visual Studio Menu.
Title Bar, Toolbar, and Menu Bar
The Title bar displays the application name and the name of the active data file (or untitled if no
data file is associated with the data being displayed).
The Menu bar displays the available menus and commands.
The Toolbar contains buttons for frequently-used commands.

Performing Basic Operations on Windows Forms


1. Setting the title of a form
2. Showing & hiding the maximize , minimize , and close buttons
3. Specifying the initial state and position of a form
4. Adding controls to a form
5. Docking & anchoring controls
6. Hiding & displaying controls
7. Setting the tab order of controls
8. Enabling & disabling controls
9. Creating a multiform windows application
1. Setting the title of a form
The text in the title bar can be set at either at run time or design time.
At design time, it can be set by changing the Text property of the form from the properties
window.
At Run time, it can be set using codes in code view.

Public Class Form1


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Me.Text = "Hello"
End Sub
End Class

2. Showing & Hiding the Maximize, Minimize and Close Buttons


A form has 3 buttons, Minimize, Maximize & Close buttons, at its Top right corner, that allow
you to minimize, maximize and close of the form. You can hide the Minimize button or
Maximize button by setting the MinimizeBox or MaximizeBox property, respectively of the
form to false.
You can hide all the three buttons Minimize , Maximize & Close by setting ControlBox property
of the form.

3. Specifying initial state & position of a form


Sometimes you are required to display a form at a specified position. You can set initial position
for a form by setting the StartPosition property of the form at either design time or run time.
The StartPosition property takes its value from the FormStartPosition enumeration.
Members of FormStartPosition are :

Manual Sets initial position of the form according to the value of Location
property
CenterScreen Positions the form at the center of the screen & sets the dimensions
of the form according to the value of the size property of the form
WindowsDefaultLocation Positions the form at the windows default location and sets the
dimensions of the form according to the value of its Size property.
This is the default value for the StartPosition property of a form
WindowsDefaultBounds Positions the form at the windows default location and sets its
dimensions according to the default settings of windows (Operating
System)
CenterParent Positions the form as centered within the bounds of its parent form

In some situation, you may also require to display a form in a fixed state, such as Normal,
Minimized, or Maximized. In such situation, you can set the initial state of the form by setting
its Windowstate property at either design or run time. The Windowstate property can be set to
any of the following values.
 Normal : sets the state of the form to the restored state. This is the default value for
the Windowstate property
 Minimized : Sets the state of the form to minimized and as a result, the form appears
on taskbar
 Maximized : Sets the state of the form to maximized and as a result it covers entire
area

4. Adding Controls to a Form


We can add controls, such as label, Button and ToolBox to our application from ToolBox to
facilitate user interaction.

Button Control
A button is used to allow the user to click on a button which would then start the processing of
the form.
Also used to rise up an event or a method.
Properties
 Name
 Anchor
 BackColor
 BackgroundImage
 Dock
 Enabled
 Font
 ForeColor
 Size
 TabIndex
 Text
 TextAlign
 Visible
Docking refers to attaching a control either to an edge (top, right, bottom or left) or the client
area of the parent control.
On the other hand, in anchoring, you specify the distance that each edge of your control
maintains from the edges of parent control.
You can set the Dock property of a control to arrange them accordingly.
You can set the Anchor property of a control for anchoring purpose.

You can make a control visible or invisible at run time. Each control has a property, named
Visible, which you can use to show or hide the control.
Controls on a form can be made accessible in an appropriate sequence by setting their
TabIndex property.
We can change the order of focusing while pressing Tab Key, by changing the TabIndex
property of a form control.

You can disable a form control element using its Enable property in the properties window. You
can set it to False if you want to disable it.
Or we can use the code to disable a form control element.

Checkbox
A checkbox is used to provide a list of options in which the user can choose multiple choices.

Properties
 Name
 Anchor
 BackColor
 BackgroundImage
 CheckAlign
 Checked
 Dock
 Enabled
 Font
 Forecolour
 Size
 TabIndex
 Text
 TextAlign
 visible

Checked List
Contains multiple checkbox items in a list

Properties
 Name
 Anchor
 BackColor
 Dock
 Enabled
 Font
 ForeColor
 Items (Collections)
 Size
 TabIndex
 Visible

ComboBox
Displays an editable text box with a drop-down list of permitted values.

Properties
 Name
 Anchor
 BackColor
 CheckAlign
 Dock
 DropDownHeight
 DropDownStyle
 DropDownWidth
 Enabled
 Font
 Forecolour
 Items (Collection)
 MaxLength
 Size
 TabIndex
 Text
 Visible

DateTimePicker
Enables the user to select a date and time, and to display that date and time in a specified
format.

Properties
 Format
 Anchor
 Font
 MinDate
 MaxDate
 Size
 TabIndex
 Value
Label
Provides run time information or a descriptive text for a control.

Properties
 Font
 FontColor
 Text
 Enabled
 Anchor
 Dock
 Visible

LinkLabel
Displays a label control that supports hyperlink functionality, formatting & tracking.

Properties

Textbox
A textbox is used for allowing a user to enter some text on the forms application.

Properties

List box
A List box is used to showcase a list of items on the Windows form.

Radio Button
A Radio button is used to showcase a list of items out of which the user can choose one.

Group Box
A group box is used for logical grouping controls into a section. GroupBox has a particular name
for that area, to categorize groups.

Panel
A Panel is used for logical grouping controls into a section. Panel has no particular name for that
area, we can create group of similar controls together without providing any name.

Accept Button & Cancel Button of a Form


Form has two special properties
1. Accept Button
2. Cancel Button
Accept button holds the event that executes when we press Enter key on keyboard.
Cancel button holds the event that executes when we press Escape key on keyboard.

We can choose these two events using two buttons. One for accept button & other for Cancel
button.

5. Docking and Anchoring Controls

6. Hiding & Displaying Controls


Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
Button1.Visible = False
End Sub
End Class

7. Setting the Tab order of controls

8. Enabling & Disabling Controls


Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
Button1.Enabled = False
End Sub
End Class

Creating a multiform Windows Application


We can add multiple forms in a project. We can add forms from Project -> Add Windows Form…
If you want to display the second form as soon as you click on the Button1 of Form1, then you
must put the code Form2.Show() for displaying the second form inside the Click event handler
of Button1 of Form1.

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
Me.Hide()
Form2.Show()
End Sub
End Class
Me.Hide() is used to hide the current form.

Setting the Startup Form in a multiform windows application


A startup form is the First form displayed when an application having two or more forms. By
default Form1 is the startup form. We can set up startup from
Project -> Properties -> Application -> Startup Form

Creating Message Boxes


A message box is a special dialog box used to display a piece of information to the user.
The function to display a messagebox is MsgBox(Parameter). Here the argument given in the
instructions are displayed in the message box, which may be a variable or a string.

Module Module1
Sub Main()
MsgBox("Displays a message as MsgBox()")
End Sub
End Module

The Return Value of a Message Box


Besides displaying a message, a message box can be used to let the user make a decision by
clicking a button and, depending on the button the user would have clicked, the message box
would return a value.
The value returned by a message box corresponds to a button the user would have clicked (on
the message box). The return value of the MsgBox() function is based on the MsgBoxResult
enumeration. The buttons and the returned values are as follows:
Button
If the User Clicks Integral Value
Caption
OK 1

Cancel 2

Abort 3

Retry 4

Ignore 5

Yes 6

No 7

The Buttons of a Message Box


If you create a simple message box by providing only the message, it would appear with only
one button labeled OK. If you want the user to be able to make a decision and communicate it
to you, provide a second argument. The second argument must be based on the MsgBoxStyle
enumeration. When it comes to buttons, some members of this enumeration are:

Integral
To Display MsgBoxStyle
Value
OKOnly 0

OKCancel 1

AbortRetryIgnore 2

YesNoCancel 3

YesNo 4

RetryCancel 5

The Caption of a Message Box


If you create a simple message box by providing only the message, the dialog box would appear
with the name of the project in the title. To allow you to specify a caption of your choice,
provide a second string as the third argument to the MsgBox() function.

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


System.EventArgs) Handles Button1.Click
Dim res As Integer
res = MsgBox("Hello How are you...???",
MsgBoxStyle.Information + MsgBoxStyle.AbortRetryIgnore, "Title")
End Sub

The Icon of a Message Box


To enhance the appearance of a message box, you can display an icon on it. To support icons,
the MsgBoxStyle enumeration provides the following additional members :
Integral
To Display MsgBoxStyle
Value

Critical 16

Question 32

Exclamation 48

Information 64

The Default Button of a Message Box


When a message box is configured to display more than one button, the operating system is set
to decide which button is the default. The default button has a thick border that sets it apart
from the other button(s). If the user presses Enter, the message box would behave as if the user
had clicked the default button. If the message box has more than one button, you can decide
what button would be the default.

If the message box


Integral contains more than one
MsgBoxStyle
Value button, the default button
would be
DefaultButton1 0 the first
DefaultButton2 256 the second
DefaultButton3 512 the third

Creating Input Boxes


An input box is a windows form like user interface similar to a message box. However, unlike a
message box, an input box accepts the input from the user. An input box can be created with
the help of the InputBox function.
An input box has 3 items, one for text input , one OK button & one Cancel Button.
An InputBox function has 3 arguments
1. Prompt: Refers to a string expression that is displayed as a message in the input box. The
maximum length for this expression is 1024 characters.
2. Title: Refers to a string expression that is displayed in the title bar of the input box.
3. Default Response: Refers to a string expression displayed in the text box as the default
response, in case no other input is provided.

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


System.EventArgs) Handles Button1.Click
Dim str As String
str = InputBox("Enter your Name", "My Application", "Azin")
TextBox1.Text = str
End Sub

Creating Dialog Boxes


A dialog box is a window that is displayed on the screen as a result of an action performed by
the user.
Properties of a dialog box:
 Add some controls , textbox, buttons, label control etc etc
 Set the FormBorderStyle property to FixedDialog
 Set the MaximizeBox property to False
 Set the MinimizeBox property to False
 Set the ShowInTaskbar property to False
 Set the DialogResult property of each buttons in the dialog box
 Double click each button & add comments to close dialog box ( Me.Close() )

Handling Common Events for windows forms control


Visual Basic 2010 is an event driven language. An event is generated whenever a user peforms
an action, for example, when the user clicks a button on a form or when the user enters some
text in a text box. The task of handling events to provide appropriate response to a user is
called event handling.
There are mainly two types of events :
1. Mouse Events
2. Keyboard Events
We can choose these events from the code window of corresponding button as shown below:

Handling Mouse Events


Mouse events represent a category of events that are generated when the user supplies the
input through a mouse. You can handle mouse events, in forms and controls.

Event Description
MouseDown Occurs when the mouse pointer is over the control and a mouse button is
pressed
MouseEnter Occurs when the mouse pointer enters the control region
MouseHover Occurs when the mouse pointer moves over the control region
Occurs when the mouse pointer leaves the control region
MouseMove Occurs when the mouse pointer moves over the control
MouseUp Occurs when the cursor of the mouse is placed on a control and the left
mouse button is released
MouseWheel Occurs when a control has focus and the wheel of the mouse moves

Handling Keyboard Events


Keyboard events represents a category of events that are generated when the user supplies the
input through a keyboard. In forms and controls , you can handle keyboard events, such as
pressing or releasing of a key.

Events Description
KeyDown Occurs when a key is pressed down while the control has focus
KeyPress Occurs when a key is pressed while the control has focus
KeyUp Occurs when a key is released while the control has focus

Using Button Control


Formatting Text in Buttons
We can format the text displaying on a button control by setting its font property. This
property can be set by using either the properties window or the code editor.
We can set the Font, Font Style, Font Size etc through this property.

Setting the background & foreground colors of buttons


We can Add background and foreground colour of a button by setting its BackColor and
ForeColor properties respectively in properties window.

Using the Label Control


The label control is used for displaying static text that you do not want to be edited by the user
or a banner containing some messages for the user. It can also be used to display dynamic text.
Dynamic text is the text that changes after the occurrence of an event in an application.
Formatting the text in Labels
We can format the text in a label by setting the font property of label using the Properties
window.
We can change the properties BackColor, ForeColor, TextAlign, Font etc from the properties
window.
Handling the click event of a Label
We can perform an action at runtime with the label control by handling its Click event in the
code. To handle the Click event of the Label control just double click the label control and then
Add comments.

Using the Textbox control


The TextBox control is a windows forms control that lets you enter a text on a windows form at
runtime. TextBox controls are mostly used when the user requires a simple text area to display
few lines of text. By default the text box control accepts only a single line of text. However, you
can make the TextBox control to accept multiple lines of text by setting Multiline property in
properties window.
We can change the properties ForeColor & BackColor properties of the textbox from the
properties window.

Using the RichTextBox Control


The RichTextBox control is used to display, enter, and manipulate text with formatting. A
RichTextBox control is similar to a TextBox control except that the RichTextBox control allows
you to perform formatting on the text that is entered in it.

Using the CheckBox Control


The CheckBox control accepts a value accepts a value in the form of either True or False. To
select a CheckBox control, you need to just click it. To clear, again click it. When you select the
CheckBox, it holds the True value and when you clear the CheckBox, it holds the False value. A
CheckBox control can display an image or corresponding text associated with it.

Using the RadioButton Control


The RadioButton control, also known an option button, is used to select one option from a set
of options. Radio buttons always work in groups. This means that whenever you select one
radio button from a group of radio buttons, the other radio buttons in the group automatically
get deselected. A radio button can display a text image or both.

Using the ComboBox Control


ComboBox is a windows control that is widely used for selecting an option from a list just as the
ListBox control; however , unlike the ListBox control, you can also enter text in the ComboBox
control. The ComboBox control is used to display data in a drop-down list. When the user has
selected an option, the drop down list contained in the ComboBox automatically collapses. A
user can choose only a single option from the list of items. You can also add or remove items
from this drop down list. Each item in a ComboBox control is recognized by its position in the
drop down list, which is known as an index.

ColorDialog & FontDialog


Used to change background color & foreground color at run time,
 Add ColorDialog from toolbox, in Dialog tab

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


System.EventArgs) Handles Button1.Click
ColorDialog1.ShowDialog()
Me.BackColor = ColorDialog1.Color()
End Sub

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


As System.EventArgs) Handles Button2.Click
ColorDialog1.ShowDialog()
Me.ForeColor = ColorDialog1.Color()
RichTextBox1.ForeColor = ColorDialog1.Color()
End Sub

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


As System.EventArgs) Handles Button3.Click
FontDialog1.ShowDialog()
Me.Font = FontDialog1.Font()
End Sub
Timer Control
Component that rises an event at a user defined intervals.
Add a timer from ToolBox  Components  Timer
Set Enabled Property to True.
Define Interval in Milliseconds in interval Property.
The event associated with timer is Tick event.

Public Class Form1


Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Timer1.Tick
ProgressBar1.Value += 10
If ProgressBar1.Value = ProgressBar1.Maximum Then
Timer1.Enabled = False
End If
If ProgressBar1.Value = 100 Then
PictureBox1.Image = Image.FromFile("D:\Photos\WallPaPers\aa.jpg")
End If
End Sub
End Class

Public Class Form1


Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Timer1.Tick
If TextBox1.BackColor = Color.Chocolate Then
TextBox1.BackColor = Color.CadetBlue
ElseIf TextBox1.BackColor = Color.CadetBlue Then
TextBox1.BackColor = Color.DarkGreen
ElseIf TextBox1.BackColor = Color.DarkGreen Then
TextBox1.BackColor = Color.DarkViolet
ElseIf TextBox1.BackColor = Color.DarkViolet Then
TextBox1.BackColor = Color.Red
ElseIf TextBox1.BackColor = Color.Red Then
TextBox1.BackColor = Color.Chocolate
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
TextBox1.BackColor = Color.Chocolate
End Sub
End Class
ToolStrip
Provides toolbars and other user interface elements that support many appearance options,
and that support overflow and run-time item reordering.
ToolBox  Menus & ToolBars  ToolStrip
We can add button, label, splitbutton, dropdownbutton, separator, textbox, progressbar.
Properties  Items
Insert standard items

MenuStrip
Displays application commands & options grouped by functionality.

Simple Calculator

Public Class Form1


Public a As Integer, b As Integer, res As Single, op As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
End Sub

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


As System.EventArgs) Handles Button2.Click
TextBox1.Text += "1"
End Sub

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


As System.EventArgs) Handles Button6.Click
TextBox1.Text += "2"
End Sub

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


As System.EventArgs) Handles Button10.Click
TextBox1.Text += "3"
End Sub

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


As System.EventArgs) Handles Button3.Click
TextBox1.Text += "4"
End Sub

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


As System.EventArgs) Handles Button7.Click
TextBox1.Text += "5"
End Sub

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


As System.EventArgs) Handles Button11.Click
TextBox1.Text += "6"
End Sub

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


As System.EventArgs) Handles Button4.Click
TextBox1.Text += "7"
End Sub

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


As System.EventArgs) Handles Button8.Click
TextBox1.Text += "8"
End Sub

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


As System.EventArgs) Handles Button12.Click
TextBox1.Text += "9"
End Sub

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


As System.EventArgs) Handles Button18.Click
TextBox1.Text += "0"
End Sub

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


As System.EventArgs) Handles Button17.Click
TextBox1.Text += "."
End Sub

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


As System.EventArgs) Handles Button20.Click
a = CInt(TextBox1.Text)
op = "/"
TextBox1.Clear()
End Sub

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


As System.EventArgs) Handles Button16.Click
a = CInt(TextBox1.Text)
op = "*"
TextBox1.Clear()
End Sub

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


As System.EventArgs) Handles Button15.Click
a = CInt(TextBox1.Text)
op = "-"
TextBox1.Clear()
End Sub

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


As System.EventArgs) Handles Button14.Click
a = CInt(TextBox1.Text)
op = "+"
TextBox1.Clear()
End Sub

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


As System.EventArgs) Handles Button9.Click
a = CInt(TextBox1.Text)
op = "%"
TextBox1.Clear()
End Sub

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


As System.EventArgs) Handles Button13.Click
Dim tmp As Integer
tmp = CInt(TextBox1.Text)
tmp = tmp \ 10
TextBox1.Text = tmp
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
TextBox1.Clear()
End Sub

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


As System.EventArgs) Handles Button19.Click
b = CInt(TextBox1.Text)
Select Case op
Case "+"
res = a + b
Case "-"
res = a - b
Case "*"
res = a * b
Case "/"
res = a / b
Case "%"
res = a Mod b
End Select
TextBox1.Text = res
End Sub
End Class
Introduction to LINQ in Visual Basic
LINQ stands for Language Integrated Query. LINQ is a data querying methodology which
provides querying capabilities to .NET languages with a syntax similar to a SQL query.
LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data
from different sources and formats. It is integrated in C# or VB, thereby eliminating the
mismatch between programming languages and databases, as well as providing a single
querying interface for different types of data sources.
For example, SQL is a Structured Query Language used to save and retrieve data from a
database. In the same way, LINQ is a structured query syntax built in C# and VB.NET to retrieve
data from different types of data sources such as collections, ADO.Net DataSet, XML Docs, web
service and MS SQL Server and other databases.

LINQ queries return results as objects. It enables you to uses object-oriented approach on the
result set and not to worry about transforming different formats of results into objects.

 LINQ to Objects: The LINQ to Objects provider enables you to query in-memory
collections and arrays.
 LINQ to DataSet: The LINQ to DataSet provider enables you to query and update data in
an ADO.NET dataset.
 LINQ to XML: The LINQ to XML provider enables you to query and modify XML. You can
modify in-memory XML, or you can load XML from and save XML to a file.
 LINQ to SQL: The LINQ to SQL provider enables you to query and modify data in a SQL
Server database. This makes it easy to map the object model for an application to the
tables and objects in a database.

Visual Basic LINQ query operators


 From clause
Either a from clause or an Aggregate clause is required to begin a query. A From clause
specifies a source collection and an iteration variable for a query.
 Select clause
A Select clause declares a set of iteration variables for a query.
 Where clause
A Where clause specifies a filtering condition for a query.
 Order By clause
An Order By clause specifies the sort order for columns in a query.
 Order By Descending Clause
An Order By Descending clause specifies the sort order for columns in a query.

Example:

Dim numqry = From a In ar Where a Mod 2 = 0 Select a


Dim sorting = From asc In numbers Order By asc Select asc
Dim sorting = From asc In numbers Order By asc Descending Select asc

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
Dim ar(100) As Integer
For i = 0 To 100
ar(i) = i
Next
Dim numqry = From a In ar Where a Mod 2 = 0 Select a
For Each num As Integer In numqry
ListBox1.Items.Add(num.ToString)
Next
End Sub
End Class
Sample Program

Public Class Form1


Public numbers() As Integer = {12, 14, 15, 75, 84, 62, 35, 41, 25,
87, 95, 43, 46, 19, 75, 72, 93, 35}, ln As Integer

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


System.EventArgs) Handles MyBase.Load
ln = numbers.Length - 1
For i = 0 To ln
ListBox1.Items.Add(numbers(i))
Next
End Sub

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


As System.EventArgs) Handles Button5.Click
ListBox2.Items.Clear()
Dim elements = From num In numbers Order By num Select num
For Each a In elements
ListBox2.Items.Add(a)
Next
End Sub

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


As System.EventArgs) Handles Button1.Click
ListBox2.Items.Clear()
Dim elements = From num In numbers Order By num Descending
Select num
For Each a In elements
ListBox2.Items.Add(a)
Next
End Sub

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


As System.EventArgs) Handles Button2.Click
ListBox2.Items.Clear()
Dim elements = From num In numbers Order By num Where num Mod
2 = 0 Select num
For Each a In elements
ListBox2.Items.Add(a)
Next
End Sub

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


As System.EventArgs) Handles Button3.Click
ListBox2.Items.Clear()
Dim elements = From num In numbers Order By num Where num Mod
2 = 1 Select num
For Each a In elements
ListBox2.Items.Add(a)
Next
End Sub

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


As System.EventArgs) Handles Button4.Click
ListBox2.Items.Clear()
Dim elements = From num In numbers Order By num Where num > 40
Select num
For Each a In elements
ListBox2.Items.Add(a)
Next
End Sub

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


As System.EventArgs) Handles Button6.Click
ListBox2.Items.Clear()
Dim elements = From num In numbers Order By num Where num < 50
Select num
For Each a In elements
ListBox2.Items.Add(a)
Next
End Sub
End Class

 Distinct clause
Optional. A Distinct clause restricts the values of the current iteration variable to
eliminate duplicate values in query results.

Вам также может понравиться