You are on page 1of 99

UNIT 1

Unit-1 Introduction to .Net framework

Introduction to Dot Net Framework

The .Net framework is a software development platform developed by Microsoft.


The first version of the .Net framework was released in the year 2002. The version was called .Net framework 1.0.
The framework was meant to create applications, which would run on the Windows Platform.
The .Net framework can be used to create both - Form-based and Web-based applications.
.NET Framework supports more than 60 programming languages in which 11 programming languages are designed and
developed by Microsoft.

Features of .NET Framework


Interoperability
Language Independence
Portability
High Performance
Memory Management
Security
Performance
Type safety
Interoperability
Each language can use code written in other languages, across several programming languages.
Language Independence
.NET Framework introduces a Common Type System (CTS) that defines all possible data
types and programming constructs Because of this feature, .NET Framework supports the exchange of types and object
instances between libraries and applications written using any conforming .NET language.
Type Safety
Type safety in .NET has been introduced to prevent the objects of one type from peeking into the memory assigned for the
other object. Writing safe code also means to prevent data loss during conversion of one type to another.
Portability
While Microsoft has never implemented the full framework on any system except Microsoft Windows, it has engineered
the framework to be cross-platform and implementations are available for other operating systems.
This makes it possible for third parties to create compatible implementations of the framework and
its languages on other platforms.
Security.NET Framework has its own security mechanism with two general features: Code Access Security (CAS), and
validation and verification.
Memory management
CLR frees the developer from the burden of managing memory (allocating and freeing up when done); it handles memory
management itself by detecting when memory can be safely freed.
When no reference to an object exists, and it cannot be reached or used, it becomes garbage, eligible for collection.
Performance
When an application is first launched, the .NET Framework compiles the CIL code into executable code using its just-in-
time compiler, and caches the executable program into the .NET Native Image Cache. Due to caching, the application
launches faster for subsequent launches, although the first launch is usually slower.
Major Components of .NET

The diagram given below describes various components of .NET Framework.

2
The bottom most layer is the CLR - the common runtime language.

Common Language Runtime (CLR)


The CLR is the heart of .NET framework. It is .NET equivalent of Java Virtual Machine (JVM). It is the runtime that
converts a MSIL (Micro Soft Intermediate Language) code into the host machine language code, which is then executed
appropriately.

The CLR provides a number of services that include:


Loading and execution of codes
Memory isolation for application
Verification of type safety
Compilation of IL into native executable code
Providing metadata
Automatic garbage collection
Enforcement of Security
Interoperability with other systems
Managing exceptions and errors
Provide support for debugging and profiling

Main components of CLR:


Common Language Specification (CLS)
Common Type System (CTS)
Garbage Collection (GC)
Just In – Time Compiler (JIT)
Common Type System (CTS)
The language interoperability, in .NET Class Framework, are not possible without all the language sharing the same data
types. What this means is that an ―int should mean the same in VB, VC++, C# and all other .NET compliant languages.
Same idea follows for all the other data types. This is achieved through introduction of Common Type System (CTS).

CTS, much like Java, defines every data type as a Class. Every .NET compliant language must stick to this definition.
Since CTS defines every data type as a class; this means that only Object- Oriented (or Object-Based) languages can
3
achieve .NET compliance. Given below is a list of CTS supported data types:

Data Type Description


System.Byte 1-byte unsigned integer between 0-255
System.Int16 2-bytes signed integer in the following range:
32,678 to 32,767
System.Int32 4-byte signed integer containing a value in the following range: -
2,147,483,648 to 2,147,483,647

System.Int64 8-byte signed integer containing a value from -


9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
4-byte floating point. The value limits are: for negative values:
-3.402823E38 to - 1.401298E-45
System.Single for positive values:
1.401298E-45 TO 30402823E38

8-bytes wide floating point. The value limits are: for negative values:
-1.79769313486231E308 to - 4.964065645841247E-
System.Double 324 for positive values:
4.964065645841247E-324 to 1.79769313486232E308

System.Object 4-bytes address reference to an object


System.Char 2-bytes single Unicode Character.
System.String string of up to 2 billion Unicode characters.
System.Decimal 12-bytes signed integer that can have 28 digits on either side of decimal.

System.Boolean 4-Bytes number that contains true(1) or false (0)

Common Language Specification (CLS)

One of the obvious themes of .NET is unification and interoperability between various programming languages. In order
to achieve this. certain rules must be laid and all the languages must follow these rules. In other words we can not have
languages running around creating their own extensions and their own fancy new data types. CLS is the collection of the
rules and constraints that every language (that seeks to achieve .NET compatibility) must follow. Microsoft has defined
three level of CLS compatibility/compliance. The goals and objectives of each compliance level have been set aside. The
three compliance levels with their brief description are given below:

Compliant producer
The component developed in this type of language can be used by any other language.

Consumer
The language in this category can use classes produced in any other language. In simple words this means that the
language can instantiate classes developed in other language. This is similar to how COM components can be instantiated
by your ASP code.

Extender
Languages in this category can not just use the classes as in CONSUMER category; but can also extend classes using
inheritance.

4
Languages that come with Microsoft Visual Studio namely Visual C++, Visual Basic and C#; all satisfy the above three
categories. Vendors can select any of the above categories as the targeted compliance level(s) for their languages.

Microsoft Intermediate Language (MSIL)

A .NET programming language (C#, VB.NET, J# etc.) does not compile into executable code; instead it compiles into an
intermediate code called Microsoft Intermediate Language (MSIL). As a programmer one need not worry about the syntax
of MSIL - since our source code in automatically converted to MSIL. The MSIL code is then send to the CLR (Common
Language Runtime) that converts the code to machine language which is then run on the host machine.
MSIL is similar to Java Byte code. A Java program is compiled into Java Byte code (the .class file) by a Java compiler, the
class file is then sent to JVM which converts it into the host machine language.
Common Language Infrastructure
It provides a virtual execution environment. It uses a compiler to process the language statement which is also known as
source code into executable code. CLI programs can be written in various programming languages like C++, C#, ASP, etc.
These all languages are compiled into CLI. CLR(by JIT) then compiles into machine code for further processing.

.NET also introduces Web Forms, Web Services and Windows Forms. The reason why they have been shown separately
and not as a part of a particular language is that these
technologies can be used by any .NET compliant language. For example Windows Forms is used by VC, VB.NET, C# all
as a mode of providing GUI.

Garbage collection

NET's garbage collector manages the allocation and release of memory for your application. Each time you create a new
object, the common language runtime allocates memory for the object from the managed heap. As long as address space is
available in the managed heap, the runtime continues to allocate space for new objects. However, memory is not infinite.
Eventually the garbage collector must perform a collection in order to free some memory. The garbage collector's
optimizing engine determines the best time to perform a collection, based upon the allocations being made. When the
garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the
application and performs the necessary operations to reclaim their memory.

Managed Code and Unmanaged code

The role of CLR doesn‘t end once we have compiled our code to MSIL and a JIT compiler has compiled this to native
code. Code written using the .NET framework, is managed code when it is executed under the control by CLR. This
means that the CLR looks after our applications, by managing memory, handling security, allowing cross language
debugging and so on. By contrast, applications that do not run under the control of the CLR are said to be unmanaged and
certain languages such as C++ can be used to write such applications, that for example, to access low level functions of the
operating systems. However in C# we can only write code that runs in a managed environment.
Just In Time Compiler
It is responsible for converting the CIL(Common Intermediate Language) into machine code or native code using the
Common Language Runtime

Framework Base Classes

The next component of .NET is the .NET Framework Base Classes. These are the common class libraries (much like Java
packages) that can be used by any .NET compliant language. These classes provide the programmers with a high degree of
functionality that they can use in their programs. For example their are classes to handle reading, writing and manipulating
XML documents, enhanced ADOs etc.
The .NET Framework has an extensive set of class libraries. This includes classes for:
Data Access: High Performance data access classes for connecting to SQL Server or any other OLEDB provider.
XML Supports: Next generation XML support that goes far beyond the functionality of MSXML.
Directory Services: Support for accessing Active Directory/LDPA using ADSI.

Regular Expression : Support for above and beyond that found in Perl 5.
5
Queuing Supports: Provides a clean object-oriented set of classes for working with MSMQ.
These class libraries use the CLR base class libraries for common functionality.

Base Class Libraries


The Base class library in the .NET Framework is huge. It covers areas such as:

Collection : The System.Collections namespaes provides numerous collection classes.


Thread Support: The System.Threading namespace provides support for creating fast, efficient, multi-threaded appliction.
Code Generation: The System.CodeDOM namespace provides classes for generating source files in numerous language.
ASP.NET uses these classes when converting ASP.NET pages into classes, which are subsequently compiled.
IO: The System.IO provides extensive support for working with files and all other stream types.
Reflection: The System.Reflection namespace provides support for load assemblies, examining the type with
in assemblies, creating instances of types, etc.
Security: The System.Security namespace provides support for services such as authentication, authorization, permission
sets, policies, and cryptography. These base services are used by application development technologies like ASP.NET to
build their security infrastructure.

Assemblies
What is an assembly?
An Assembly is a logical unit of code
Assembly physically exist as DLLs or EXEs
One assembly can contain one or more files
The constituent files can include any file types like image files, text files etc. along with DLLs or EXEs
When you compile your source code by default the exe/dll generated is actually an assembly
Unless your code is bundled as assembly it cannot be used in any other application
When you talk about version of a component you are actually talking about version of the assembly to which the
component belongs.
Every assembly file contains information about itself. This information is called as Assembly Manifest.

assembly manifest

Assembly manifest is a data structure which stores information about an assembly


This information is stored within the assembly file(DLL/EXE) itself.
The information includes version information, list of constituent files etc.
What is private and shared assembly?

The assembly which is used only by a single application is called as private assembly. Suppose you created a DLL which
encapsulates your business logic. This DLL will be used by your client application only and not by any other application.
In order to run the application properly your DLL must reside in the same folder in which the client application is
installed. Thus the assembly is private to your application.
Suppose that you are creating a general purpose DLL which provides functionality which will be used by variety of
applications. Now, instead of each client application having its own copy of DLL you can place the DLL in 'global
assembly cache'. Such assemblies are called as shared assemblies.

Global Assembly Cache

Global assembly cache is nothing but a special disk folder where all the shared assemblies will be kept. It is located under
<drive>:\WinNT\Assembly folder.

Managed Execution Process

The managed execution process includes the following steps;-


6
Choosing a compiler. To obtain the benefits provided by the common language runtime, you must use one or more
language compilers that target the runtime
Compiling your code to MSIL.
Compiling translates your source code into Microsoft intermediate language (MSIL) and generates the required metadata.
Compiling MSIL to native code.
At execution time, a just-in-time (JIT) compiler translates the MSIL into native code. During this compilation, code must
pass a verification process that examines the MSIL and metadata to find out whether the code can be determined to be type
safe.
Running code.
The common language runtime provides the infrastructure that enables execution to take place and services that can be
used during execution.
Language Interoperability can be achieved in two ways:

Managed Code: The MSIL code which is managed by the CLR is known as the Managed Code. For managed code CLR
provides three .NET facilities:
(Code Access Security)
Exception Handling
Automatic Memory Management.

Unmanaged Code: Before .NET development the programming language like .COM Components & Win32 API does not
generate the MSIL code. So these are not managed by CLR rather managed by Operating System.

Programming Languages which are designed and developed by Microsoft are:


C#.NET
VB.NET
C++.NET
J#.NET
F#.NET
JSCRIPT.NET
WINDOWS POWERSHELL
IRON RUBY
IRON PYTHON
C OMEGA
ASML(Abstract State Machine Language)

7
Unit-2

UNIT 2

8
Unit-2

Data Types

Data types determine the type of data that any variable can store. Variables belonging to different data types are allocated
different amounts of space in the memory. There are various data types in VB.NET. They include:
Different Data Types and their allocating spaces in VB.NET
The following table shows the various data types list in the VB.NET programming language.
DataTypes Required Space Value Range

Boolean A Boolean type depends True or False


on the implementing
platform

Byte 1 byte Byte Range start from 0 to 255 (unsigned)

Char 2 bytes Char Range start from 0 to 65535 (unsigned)

Date 8 bytes Date range can be 0:00:0 (midnight) January 1, 0001 to 11:5959
PM of December 31, 9999.

Decimal 16 bytes Range from 0 to +/-79,228,162,514,264,337,593,543,950,335


(+/-7.9…E+28) without any decimal point;
And 0 to +/-7.92281625142264337593543950335 with 28 position
to the right of the decimal

Double 8 bytes -1.79769313486231570E+308 to -4.94-65645841246544E-324 for


negative values;
4.94065645841246544E-324 to 1.79769313486231570E+308, for
positive values

Integer 4 bytes -2,147,483,648 to 2,147,483,647 (signed)

Long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (9.2…


E + 18) (signed)

Object Object size based on the It can store any type of data defined in a variable of type Object
platform such as 4 bytes
in 32-bit and 8 bytes in
64-bit platform

SByte 1 byte -128 to 127 (signed)

Short 2 bytes -32,768 to 32,767 (signed)

Single 4 bytes -3.4028235E + 38 to -1.401298E-45 for negative values;


And for positive value: 1.401298E-45 to 3.4028235E + 38.

String String Datatype depend It accepts Unicode character from 0 to approximately 2 billion
on the implementing characters.
platform

9
VB.NET Variable and Constant
In VB.NET, a variable is used to hold the value that can be used further in the programming. In this section, we will learn
how to declare and initialize a variable and a constant.

Variable

A variable is a simple name used to store the value of a specific data type in computer memory. In VB.NET, each variable
has a particular data type that determines the size, range, and fixed space in computer memory. With the help of variable,
we can perform several operations and manipulate data values in any programming language.
VB.NET Variables Declaration
The declaration of a variable is

simple that requires a variable name and data type followed by a Dim. A Dim is used in Class, Module, structure, Sub,
procedure.
Syntax:
Dim [Variable_Name] As [Defined Data Type]
Name Descriptions

Dim It is used to declare and allocate the space for one or more variables in memory.

It defines the name of the variable to store the values.


Variable_Name

As It is a keyword that allows you to define the data type in the declaration statement.

Data Type It defines a data type that allows variables to store data types such as Char, String,
Integer, Decimal, Long, etc.

Value Assign a value to the variable.

There are some valid declarations of variables along with their data type definition, as shown below:

Dim Roll_no As Integer


Dim Emp_name As String
Dim Salary As Double
Dim Emp_id, Stud_id As Integer
Dim result_status As Boolean
Further, if we want to declare more than one variable in the same line, we must separate each variable with a comma.
Syntax
Dim Variable_name1 As DataType1, variable_name2 As DataType2, Variable_name3 As DataType3
Note: The statements given below is also used to declare the variable with their data type:
Static name As String
Public bill As Decimal = 0
VB.NET Variable Initialization
After the declaration of a variable, we must assign a value to the variable. The following syntax describes the initialization
of a variable:
Syntax:
Variable_name = value
For example:
Dim Roll_no As Integer 'declaration of Roll_no
Roll_no = 101 'initialization of Roll_no

Initialize the Emp_name


Dim Emp_name As String
10
Emp_name = "Vikas" 'Here Emp_name variable assigned a value of Vikas

Initialize a Boolean variable


Dim status As Boolean 'Boolean value can be True or False.
status = True 'Initialize status value to True
We can also initialize a variable at the time of declaration:
Dim Roll_no As Integer = 101
Dim Emp_name As String = "Ram "
Let's create a program to use different types of variable declaration and initialization in VB.NET.
Variable1.vb
Imports System
Module Variable1
Sub Main()
'declaration of intData as Integer
Dim intData As Integer
'declaration of charData as Char
Dim CharData As Char
'declaration of strData as String
Dim strData As String
'declaration of dblData as Double
Dim dblData As Double
'declaration of single_data as Single
Dim single_data As Single
'Initialization of intData
intData = 10
'Initialization of CharData
CharData = "A"
'Initialization of strData
strData = " VB.NET is a Programming Language."
dblData = 4567.676
'Initialization of dblData
'Initialization of single_data
single_data = 23.08
Console.WriteLine(" Value of intData is: {0}", intData)
Console.WriteLine(" Value of CharData is: {0}", CharData)
Console.WriteLine(" Value of strData is: {0}", strData)
Console.WriteLine(" Value of dblData is: {0}", dblData)
Console.WriteLine(" Value of single_data is: {0}", single_data)

Console.WriteLine("press any key to exit...")


Console.ReadKey()
End Sub

End Module
Output:
Value of intData is: 10
Value of CharData is: A
Value of strData is: VB.NET is a Programming Language.
Value of dblData is: 4567.676
Value of single_data is: 23.08
press any key to exit...

Getting Values from the User in VB.NET


In VB.NET, the Console class provides the Readline() function in the System namespace. It is used to take input from the
user and assign a value to a variable. For example:
11
Dim name As String
name = Console.ReadLine()
Or name = Console.ReadLine
Let's create a program that takes input from the user.
User_Data.vb
Imports System
Module User_Data
Sub Main()
Dim num As Integer
Dim age As Double
Dim name As String
Console.WriteLine("Enter your favourite number")
' Console.ReadLine or Console.ReadLine() takes value from the user
num = Console.ReadLine
Console.WriteLine(" Enter Your Good name")
'Read string data from the user
name = Console.ReadLine
Console.WriteLine(" Enter your Age")
age = Console.ReadLine
Console.WriteLine(" You have entered {0}", num)
Console.WriteLine(" You have entered {0}", name)
Console.WriteLine(" You have entered {0}", age)
Console.ReadKey()

End Sub
End Module

VB.NET Constants
As the name suggests, the name constant refers to a fixed value that cannot be changed during the execution of a program.
It is also known as literals. These constants can be of any data type, such as Integer, Double, String, Decimal, Single,
character, enum, etc.

Declaration of Constants
In VB.NET, const is a keyword that is used to declare a variable as constant. The Const statement can be used with
module, structure, procedure, form, and class.

Syntax:
Const constname As datatype = value

ItemName Descriptions

Const It is a Const keyword to declare a variable as constant.

Constname It defines the name of the constant variable to store the values.

As It is a keyword that allows you to define the data type in the declaration statement.

Data Type It defines a data type that allows variables to store data types such as Char, String,
Integer, Decimal, Long, etc.

Value Assign a value to the variable as constant.

Further, if we want to declare more than one variable in the same line, we must separate each variable with a comma, as
shown below. The Syntax for defining the multiple variables as constant is:
Dim Variable_name1 As DataType1, variable_name2 As DataType2, Variable_name3 As DataType3
12
Note: The statements given below are also used to declare the variable with their data type:
Const num As Integer = 10
Static name As String
Public Const name As String = "Disha College"
Private Const PI As Double = 3.14

Module variablesNdataypes
Sub Main()
Dim a As Short
Dim b As Integer
Dim c As Double

a = 10
b = 20
c=a+b
Console.WriteLine("a={0},b={1},c={2}", a, b, c)
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −
a = 10, b = 20, c = 30
Accepting Values from User

The Console class in the System namespace provides a function ReadLine for accepting input from the user and store it
into a variable. For example,
Dim message As String
message = Console.ReadLine

The following example demonstrates it −

Module variablesNdataypes
Sub Main()
Dim message As String
Console.Write("Enter message: ")
message = Console.ReadLine
Console.WriteLine()
Console.WriteLine("Your Message: {0}", message)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result (assume the user inputs Hello World) −
Enter message: Hello World
Your Message: Hello World

Type Conversion Functions

There are functions that we can use to convert from one data type to another. They include:
CBool (expression): converts the expression to a Boolean data type.
CDate(expression): converts the expression to a Date data type.
CDbl(expression): converts the expression to a Double data type.
CByte (expression): converts the expression to a byte data type.
CChar(expression): converts the expression to a Char data type.
CLng(expression): converts the expression to a Long data type.
CDec(expression): converts the expression to a Decimal data type.
CInt(expression): converts the expression to an Integer data type.
13
CObj(expression): converts the expression to an Object data type.
CStr(expression): converts the expression to a String data type.
CSByte(expression): converts the expression to a Byte data type.
CShort(expression): converts the expression to a Short data type.
Module Module1

Sub Main()

Dim dblData As Double


dblData = 5.78
Dim num As Integer

num = CInt(dblData)
Console.WriteLine(" Value of Double is: {0}", dblData)
Console.WriteLine("Double to Integer: {0}", num)
Console.ReadKey()

End Sub

End Module

Operator

An operator refers to a symbol that instructs the compiler to perform a specific logical or mathematical manipulation. The
operator performs the operation on the provided operands.
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. VB.Net is rich
in built-in operators and provides following types of commonly used operators −
Arithmetic Operators
Comparison Operators
Logical/Bitwise Operators
Bit Shift Operators
Assignment Operators
Arithmetic Operators
You can use arithmetic operators to perform various mathematical operations in VB.NET. They include:

Symbol Description

^ for raising an operand to the power of another


operand

+ for adding two operands.

- for subtracting the second operand from the first


operand.

* for multiplying both operands.

/ for dividing an operand against another. It returns


a floating point result.

\ for dividing an operand against another. It returns


an integer result.

MOD known as the modulus operator. It returns the


remainder after division.
14
Module Module1

Sub Main()
Dim var_w As Integer = 11
Dim var_x As Integer = 5
Dim var_q As Integer = 2
Dim var_y As Integer
Dim var_z As Single
var_y = var_w + var_z
Console.WriteLine(" Result of 11 + 5 is {0} ", var_y)
var_y = var_w - var_x
Console.WriteLine(" Result of 11 - 5 is {0} ", var_y)
var_y = var_w * var_x
Console.WriteLine(" Result of 11 * 5 is {0} ", var_y)
var_z = var_w / var_x
Console.WriteLine(" Result of 11 / 5 is {0}", var_z)
var_y = var_w \ var_x
Console.WriteLine(" Result of 11 \ 5 is {0}", var_y)
var_y = var_w Mod var_x
Console.WriteLine(" Result of 11 MOD 5 is {0}", var_y)

var_y = var_x ^ var_x


Console.WriteLine(" Result of 5 ^ 5 is {0}", var_y)
Console.ReadLine()

End Sub

End Module

Comparison Operators
These operators are used for making comparisons between variables. They include the following:
Comparison Operators Details

= for checking whether the two operands have equal


values or not. If yes, the condition will become
true.

<> for checking if the value of the left operand is


greater than that of the right operand. then
condition will become true.

> for checking whether the value of the left operand


is less than that of the right operand. If yes, the
15
condition will become true.

< for checking whether the value of the left operand


is greater than or equal to that of the right
operand. If yes, the condition will become true.

>= for checking whether the two operands have equal


values or not. If yes, the condition will become
true.

<= for checking whether the value of the left operand


is less than or equal to that of the right operand. If
yes, the condition will become true.

Module Module1

Sub Main()
Dim x As Integer = 11
Dim y As Integer = 5
If (x = y) Then
Console.WriteLine("11=5 is True")
Else
Console.WriteLine(" 11=5 is False")
End If

If (x < y) Then
Console.WriteLine(" 11<5 is True")
Else
Console.WriteLine(" 11<5 is False")
End If

If (x > y) Then
Console.WriteLine(" 11>5 is True")
Else
Console.WriteLine(" 11>5 is False")
End If

x=3
y=7
If (x <= y) Then
Console.WriteLine(" 3<=7 is True")
End If
If (y >= x) Then
Console.WriteLine(" 7>=3 is True")
End If
Console.ReadLine()

End Sub

End Module

16
Logical/Bitwise Operators

These operators help us in making logical decisions.


They include:
Logical/ Bite Descriptions
wise Operator

And known as the logical/bitwise AND. Only true when both conditions are true.

Or known as the logical/bitwise OR. True when any of the conditions is true.

Not The logical/bitwise NOT. To reverse operand's logical state. If true, the condition becomes
False and vice versa.

Xor bitwise Logical Exclusive OR operator. Returns False if expressions are all True or False.
Otherwise, it returns True.

AndAlso It is also known as the logical AND operator. Only works with Boolean data by performing
short-circuiting.

OrElse It is also known as the logical OR operator. Only works with Boolean data by performing
short-circuiting.

IsFalse Determines whether expression evaluates to False.

IsTrue Determines whether expression evaluates to True.

Module Module1

Sub Main()

Dim var_w As Boolean = True


Dim var_x As Boolean = True
Dim var_y As Integer = 5
Dim var_z As Integer = 20

If (var_w And var_x) Then


Console.WriteLine("var_w And var_x - is true")
End If
If (var_w Or var_x) Then
Console.WriteLine("var_w Or var_x - is true")
End If
17
If (var_w Xor var_x) Then
Console.WriteLine("var_w Xor var_x - is true")
End If
If (var_y And var_z) Then
Console.WriteLine("var_y And var_z - is true")
End If
If (var_y Or var_z) Then
Console.WriteLine("var_y Or var_z - is true")
End If
'Only logical operators
If (var_w AndAlso var_x) Then
Console.WriteLine("var_w AndAlso var_x - is true")
End If
If (var_w OrElse var_x) Then
Console.WriteLine("var_w OrElse var_x - is true")
End If
var_w = False
var_x = True
If (var_w And var_x) Then
Console.WriteLine("var_w And var_x - is true")
Else
Console.WriteLine("var_w And var_x - is not true")
End If
If (Not (var_w And var_x)) Then
Console.WriteLine("var_w And var_x - is true")
End If
Console.ReadLine()
End Sub
End Module

Bit Shift Operators


These operators are used for performing shift operations on binary values.
Bit-shit operatiors Details

And Known as the Bitwise AND Operator. It copies


a bit to result if it is found in both operands.

Or Known as the Binary OR Operator. It copies


a bit if found in either operand.

Xor The Binary XOR Operator. For copying a bit


if set in one of the operands rather than both.

Not It is known as the Binary Ones Complement Operator.


It is a unary operator that 'flips' the bits.
18
Module Module1

Sub Main()

Dim w As Integer = 50
Dim x As Integer = 11
Dim y As Integer = 0
y = w And x
Console.WriteLine("y = w And x is {0}", y)
y = w Or x

Console.WriteLine("y = w Or x is {0}", y)
y = w Xor x

Console.WriteLine("y = w Xor x is {0}", y)


y = Not w

Console.WriteLine("y = Not w is {0}", y)


Console.ReadLine()

End Sub
End Module

Assignment Operators
Assignment Operator Details

= the simple assignment operator. It will assign


values from the left side operands to the right side
operands.

+= known as the Add AND assignment operator. It


will add the right operand to the left operand.
Then the result will be assigned to the left
operand.

= known as the Subtract AND operator. It will


subtract the right operand from left operand and
assign the result to the left operand.

*= : known as the Multiply AND operator. It will


subtract the right operand from left operand and
assign the result to the left operand.

19
Module Module1

Sub Main()

Dim x As Integer = 5
Dim y As Integer
y=x
Console.WriteLine(" y = x gives y = {0}", y)
y += x
Console.WriteLine(" y += x gives y = {0}", y)
y -= x
Console.WriteLine(" y -= x gives y = {0}", y)
y *= x
Console.WriteLine(" y *= x gives y = {0}", y)
Console.ReadLine()
End Sub

End Module

Operator Precedence in VB.NET

Operator precedence is used to determine the order in which different Operators in a complex expression are evaluated.
There are distinct levels of precedence, and an Operator may belong to one of the levels. The Operators at a higher level of
precedence are evaluated first. Operators of similar precedents are evaluated at either the left-to-right or the right-to-left
level.
The Following table shows the operations, Operators and their precedence -
Operations Operators Precedence

Await Highest

Exponential ^

Unary identity and negation +, -

Multiplication and floating-point *, /


division

Integer division \

Modulus arithmetic Mod

Addition and Subtraction +, -

Arithmetic bit shift <<, >>

All comparison Operators =, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf
…is
20
Negation Not

Conjunction And, AndAlso

Inclusive disjunction Or, Else

Exclusive disjunction Xor Lowest

Example of Operator Precedence in VB.NE


Imports System
Module Operator_Precedence
Sub Main()
'Declare and Initialize p, q, r, s variables
Dim p As Integer = 30
Dim q As Integer = 15
Dim r As Integer = 10
Dim s As Integer = 5
Dim result As Integer

Console.WriteLine("Check Operator Precedence in VB.NET")


'Check Operator Precedence
result = (p + q) * r / s ' 45 * 10 / 5
Console.WriteLine("Output of (p + q) * r / s is : {0}", result)

result = (p + q) * (r / s) ' (45) * (10/5)


Console.WriteLine("Output of (p + q) * (r / s) is : {0}", result)

result = ((p + q) * r) / s ' (45 * 10 ) / 5


Console.WriteLine("Output of ((p + q) * r) / s is : {0}", result)

result = p + (q * r) / s ' 30 + (150/5)


Console.WriteLine("Output of p + (q * r) / s is : {0}", result)

result = ((p + q * r) / s) ' ((30 + 150) /5)


Console.WriteLine("Output of ((p + q * r) / s) is : {0}", result)

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module

If...Then Statement
It is the simplest form of control statement, frequently used in decision making and changing the control flow of the
program execution. Syntax for if-then statement is −
If condition Then
[Statement(s)]
End If
Where, condition is a Boolean or relational condition and Statement(s) is a simple or compound statement. Example of an
If-Then statement is −
If (a <= 20) Then
c= c+1
End If
If the condition evaluates to true, then the block of code inside the If statement will be executed. If condition evaluates to
false, then the first set of code after the end of the If statement (after the closing End If) will be executed.
21
Example
Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 10

' check the boolean condition using if statement


If (a < 20) Then
' if condition is true then print the following
Console.WriteLine("a is less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a is less than 20
value of a is : 10

If...Then...Else Statement

An If statement can be followed by an optional Else statement, which executes when the Boolean expression is false.
Syntax
The syntax of an If...Then... Else statement in VB.Net is as follows −
If(boolean_expression)Then
'statement(s) will execute if the Boolean expression is true
Else
'statement(s) will execute if the Boolean expression is false
End If
If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be
executed.
Example
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100

' check the boolean condition using if statement


If (a < 20) Then
' if condition is true then print the following
Console.WriteLine("a is less than 20")
Else
' if condition is false then print the following
Console.WriteLine("a is not less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −
a is not less than 20
value of a is : 100
The If...Else If...Else Statement
An If statement can be followed by an optional Else if...Else statement, which is very useful to test various conditions
using single If...Else If statement.
22
When using If... Else If... Else statements, there are few points to keep in mind.
An If can have zero or one Else's and it must come after an Else If's.
An If can have zero to many Else If's and they must come before the Else.
Once an Else if succeeds, none of the remaining Else If's or Else's will be tested.

Syntax
The syntax of an if...else if...else statement in VB.Net is as follows −
If(boolean_expression 1)Then
' Executes when the boolean expression 1 is true
ElseIf( boolean_expression 2)Then
' Executes when the boolean expression 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the boolean expression 3 is true
Else
' executes when the none of the above condition is true
End If
Example
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100
' check the boolean condition '
If (a = 10) Then
' if condition is true then print the following '
Console.WriteLine("Value of a is 10") '
ElseIf (a = 20) Then
'if else if condition is true '
Console.WriteLine("Value of a is 20") '
ElseIf (a = 30) Then
'if else if condition is true
Console.WriteLine("Value of a is 30")
Else
'if none of the conditions is true
Console.WriteLine("None of the values is matching")
End If
Console.WriteLine("Exact value of a is: {0}", a)
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −
None of the values is matching
Exact value of a is: 100

Nested If Statements
It is always legal in VB.Net to nest If-Then-Else statements, which means you can use one If or ElseIf statement inside
another If ElseIf statement(s).
Syntax
The syntax for a nested If statement is as follows −
If( boolean_expression 1)Then
'Executes when the boolean expression 1 is true
If(boolean_expression 2)Then
'Executes when the boolean expression 2 is true
End If
End If
You can nest ElseIf...Else in the similar way as you have nested If statement.
23
Example
Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
' check the boolean condition

If (a = 100) Then
' if condition is true then check the following
If (b = 200) Then
' if condition is true then print the following
Console.WriteLine("Value of a is 100 and b is 200")
End If
End If
Console.WriteLine("Exact value of a is : {0}", a)
Console.WriteLine("Exact value of b is : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

Select Case Statement

A Select Case statement allows a variable to be tested for equality against a list of values. Each value is called a case, and
the variable being switched on is checked for each select case.
Syntax

The syntax for a Select Case statement in VB.Net is as follows −


Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Where,
expression − is an expression that must evaluate to any of the elementary data type in VB.Net, i.e., Boolean, Byte, Char,
Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, and UShort.
expressionlist − List of expression clauses representing match values for expression. Multiple expression clauses are
separated by commas.
statements − statements following Case that run if the select expression matches any clause in expressionlist.
elsestatements − statements following Case Else that run if the select expression does not match any clause in
the expressionlist of any of the Case statements.

Example
Module decisions
Sub Main()
'local variable definition
Dim grade As Char
grade = "B"
Select grade
Case "A"
24
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select
Console.WriteLine("Your grade is {0}", grade)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B

For Next Loop

A For Next loop is used to repeatedly execute a sequence of code or a block of code until a given condition is satisfied. A
For loop is useful in such a case when we know how many times a block of code has to be executed. In VB.NET, the For
loop is also known as For Next Loop.
Syntax
For variable_name As [ DataType ] = start To end [ Step step ]
[ Statements to be executed ]
Next

Example 1. Write a simple program to print the number from 1 to 10 using the For Next loop.
Number.vb
Imports System
Module Module1
Sub Main()
' It is a simple print statement, and 'vbCrLf' is used to jump in the next line.
Console.Write(" The number starts from 1 to 10 " & vbCrLf)
' declare and initialize variable i
For i As Integer = 1 To 10 Step 1
' if the condition is true, the following statement will be executed
Console.WriteLine(" Number is {0} ", i)
' after completion of each iteration, next will update the variable counter
Next
Console.WriteLine(" Press any key to exit... ")
Console.ReadKey()
End Sub
End Module
Output:

25
Example 2. Write the following program to skip the number is 2.
Number.vb
Imports System
Module Number
Sub Main()
' declaration of variable i
Dim i As Integer
Console.Write(" Skip one number at the completion of each iteration in between 1 to 10 " & vbCrLf)
' initialize i to 1 and declare Step to 2 for skipping a number
For i = 1 To 10 Step 2
' if condition is true, it skips one number
Console.WriteLine(" Number is {0} ", i)
' after completion of each iteration, next will update the variable counter to step 2
Next
Console.WriteLine(" Press any key to exit... ")
Console.ReadKey()
End Sub
End Module
Output:

Nested For Next Loop in VB.NET

In VB.NET, when we write one For loop inside the body of another For Next loop, it is called Nested For Next loop.
Syntax:
For variable_name As [Data Type] = start To end [ Step step ]
For variable_name As [Data Type] = start To end [ Step step ]
[ inner loop statements ]
Next
[ Outer loop statements ]
Next
Example of Nested For Next loop in VB.NET. 26
Nested_loop.vb
Imports System
Module Nested_loop
Sub Main()
Dim i, j As Integer
For i = 1 To 3
'Outer loop
Console.WriteLine(" Outer loop, i = {0}", i)
'Console.WriteLine(vbCrLf)

'Inner loop
For j = 1 To 4
Console.WriteLine(" Inner loop, j = {0}", j)
Next
Console.WriteLine()
Next
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:

VB.NET For Each Loop

In the VB.NET, For Each loop is used to iterate block of statements in an array or collection objects. Using For Each loop,
we can easily work with collection objects such as lists, arrays, etc., to execute each element of an array or in a collection.
And when iteration through each element in the array or collection is complete, the control transferred to the next
statement to end the loop.
Syntax:
For Each var_name As [ DataType ] In Collection_Object
[ Statements to be executed]
Next
For Each loop is used to read each element from the collection object or an array. The Data Type represents the type of the
variable, and var_name is the name of the variable to access elements from the array or collection object so that it can be
used in the body of For Each loop.
Examples of For Each Loop
27
Write a simple program to understand the uses of For Each Next loop in VB.NET.
For_Each_loop.vb
Imports System
Module For_Each_loop
Sub Main()
'declare and initialize an array as integer
Dim An_array() As Integer = {1, 2, 3, 4, 5}
Dim i As Integer 'Declare i as Integer

For Each i In An_array


Console.WriteLine(" Value of i is {0}", i)
Next
Console.WriteLine("Press any key to exit...")
Console.ReadLine()
End Sub
End Module

Output:

Example 2: Write a simple program to print fruit names using For Each loop in VB.NET.
For_each.vb
Imports System
Module For_each
Sub Main()
'Define a String array
Dim str() As String

'Initialize all element of str() array


str = {"Apple", "Orange", "Mango", "PineApple", "Grapes", "Banana"}

Console.WriteLine("Fruit names are")

'Declare variable name as fruit


For Each fruit As String In str
Console.WriteLine(fruit)
Next
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:

28
VB.NET While End Loop

The While End loop is used to execute blocks of code or statements in a program, as long as the given condition is true. It
is useful when the number of executions of a block is not known. It is also known as an entry-controlled loop statement,
which means it initially checks all loop conditions. If the condition is true, the body of the while loop is executed. This
process of repeated execution of the body continues until the condition is not false. And if the condition is false, control is
transferred out of the loop.
Syntax:
While [condition]
[ Statement to be executed ]
End While
Here, condition represents any Boolean condition, and if the logical condition is true, the single or block of
statements define inside the body of the while loop is executed.
Example: Write a simple program to print the number from 1 to 10 using while End loop in VB.NET.
while_number.vb
Imports System
Module while_number
Sub Main()
'declare x as an integer variable
Dim x As Integer
x=1
' Use While End condition
While x <= 10
'If the condition is true, the statement will be executed.
Console.WriteLine(" Number {0}", x)
x = x + 1 ' Statement that change the value of the condition
End While
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:

29
Example 2: Write a program to print the sum of digits of any number using while End loop in VB.NET.
Total_Sum.vb
Public Class Total_Sum ' Create a Class Total_sum
Shared Sub Main()
'Declare an Integer variable
Dim n, remainder, sum As Integer
sum = 0

Console.WriteLine(" Enter the number :")


n = Console.ReadLine() ' Accept a number from the user

' Use While loop and write given below condition


While (n > 0)
remainder = n Mod 10
sum += remainder
n = n / 10
End While
Console.WriteLine(" Sum of digit is :{0}", sum)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Class
Output:

Do While Loop

In VB.NET, Do While loop is used to execute blocks of statements in the program, as long as the condition remains true.
It is similar to the While End Loop, but there is slight difference between them. The while loop initially checks the defined
condition, if the condition becomes true, the while loop's statement is executed. Whereas in the Do loop, is opposite of the
while loop, it means that it executes the Do statements, and then it checks the condition.
Syntax:
Do
[ Statements to be executed]
30
Loop While Boolean_expression
// or
Do
[Statement to be executed]
Loop Until Boolean_expression
In the above syntax, the Do keyword followed a block of statements, and While keyword checks Boolean_expression after
the execution of the first Do statement.
Example 1. Write a simple program to print a number from 1 to 10 using the Do While loop in VB.NET.
Do_loop.vb
Imports System
Module Do_loop
Sub Main()
' Initializatio and Declaration of variable i
Dim i As Integer = 1
Do
' Executes the following Statement
Console.WriteLine(" Value of variable I is : {0}", i)
i = i + 1 'Increment the variable i by 1
Loop While i <= 10 ' Define the While Condition

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module
Now compile and execute the above program by clicking on the Start button, it shows the following output:

Use of Until in Do Until Loop statement

In the VB.NET loop, there is a Do Until loop statement, which is similar to the Do While loop. The Do Statement executes
as long as Until condition becomes true.
Example: Write a program to understand the uses of Do Until Loop in VB.NET.
Do_loop.vb
Imports System
Module Do_loop
Sub Main()
' Initialization and Declaration of variable i
Dim i As Integer = 1
Do
' Executes the following Statement
Console.WriteLine(" Value of variable i is : {0}", i)
i = i + 1 'Increment variable i by 1
Loop Until i = 10 ' Define the Until Condition

31
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:

Arrays

An array is a linear data structure that is a collection of data elements of the same type stored on a contiguous
memory location. Each data item is called an element of the array. It is a fixed size of sequentially arranged elements in
computer memory with the first element being at index 0 and the last element at index n - 1, where n represents the total
number of elements in the array.
The following is an illustrated representation of similar data type elements defined in the VB.NET array data structure.
In the above diagram, we store the Integer type data elements in an array starting at index 0. It will continue to store data
elements up to a defined number of elements.
Declaration of VB.NET Array
We can declare an array by specifying the data of the elements followed by parentheses () in the VB.NET.
Dim array_name As [Data_Type] ()
In the above declaration, array_name is the name of an array, and the Data_Type represents the type of element (Integer,
char, String, Decimal) that will to store contiguous data elements in the VB.NET array.
Now, let us see the example to declare an array.
'Store only Integer values
Dim num As Integer() or Dim num() As Integer
'Store only String values
Dim name As String() or Dim name(5) As String
' Store only Double values
Dim marks As Double()
Initialization of VB.NET Array
In VB.NET, we can initialize an array with New keyword at the time of declaration. For example,
'Declaration and Initialization of an array elements with size 6
Dim num As Integer() = New Integer(5) { }
Dim num As Integer() = New Integer(5) {1, 2, 3, 4, 5, 6}
Initialize an array with 5 elements that indicates the size of an array
Dim arr_name As Integer() = New Integer() {5, 10, 5, 20, 15}
Declare an array
Dim array1 As Char()
array1 = New Char() {'A', 'B', 'C', 'D', 'E'}
Furthermore, we can also initialize and declare an array using the following ways, as shown below.
Dim intData() As Integer = {1, 2, 3, 4, 5}
Dim intData(5) As Integer
Dim array_name() As String = {"Peter", "John", "Brock", "James", "Maria"}
Dim misc() as Object = {"Hello friends", 16c, 12ui, "A"c}
32
Dim Emp(0 to 2) As String
Emp{0} = "Mathew"
Emp(1) = " Anthony"
Emp(2) = "Prince"
Let's create a program to add the elements of an array in VB.NET programming language.
num_Array.vb
Imports System
Module num_Array
Sub Main()
Dim i As Integer, Sum As Integer = 0
Dim marks() As Integer = {58, 68, 95, 50, 23, 89}
Console.WriteLine(" Marks in 6 Subjects")

For i = 0 To marks.Length - 1
Console.WriteLine(" Marks {0}", marks(i))
Sum = Sum + marks(i)
Next

Console.WriteLine(" Grand total is {0}", Sum)

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module
Output:

Input number in

VB.NET Array

Let's create a program to take input values from the user and display them in VB.NET programming language.
Input_array.vb
Imports System
Module Input_array
Sub Main()
'Definition of array
Dim arr As Integer() = New Integer(6) {}

For i As Integer = 0 To 5
Console.WriteLine(" Enter the value for arr[{0}] : ", i)
arr(i) = Console.ReadLine() ' Accept the number in array
Next

Console.WriteLine(" The array elements are : ")


' Definition of For loop
For j As Integer = 0 To 5
Console.WriteLine("{0}", arr(j))
33
Next

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module
Output:

Dynamic Array

A Dynamic array is used when we do not know how many items or elements to be inserted in an array. To resolve this
problem, we use the dynamic array. It allows us to insert or store the number of elements at runtime in sequentially
manner. A Dynamic Array can be resized according to the program's requirements at run time using
the "ReDim" statement.
Initial Declaration of Array
Syntax:
Dim array_name() As Integer
Runtime Declaration of the VB.NET Dynamic array (Resizing)
Syntax:
ReDim [Preserve] array_name(subscripts)
The ReDim statement is used to declare a dynamic array. To resize an array, we have used a Preserve keyword that
preserve the existing item in the array. The array_name represents the name of the array to be re-dimensioned.
A subscript represents the new dimension of the array.
Initialization of Dynamic Array
Dim myArr() As String
ReDim myArr(3)
myArr(0) = "One"
myArr(1) = "Two"
myArr(2) = "Three"
myArr(3) = "Four"
To initialize a Dynamic Array, we have used create a string array named myArr() that uses the Dim statement in which we
do not know the array's actual size. The ReDim statement is used to resize the existing array by defining the subscript (3).
If we want to store one more element in index 4 while preserving three elements in an array, use the following statements.
ReDim Preserve myArr(4)
myArr(4) = "Five"
the above array has four elements.
Also, if we want to store multiple data types in an array, we have to use a Variant data type.
Dim myArr() As Variant
ReDim myArr(3)
myArr(0) = 10
34
myArr(0) = "String"
myArr(0) = false
myArr(0) = 4.6
Let's create a program to understand the dynamic array.
Dynamic_Arr.vb
Imports System
Module Dynamic_Arr
Sub Main()
Dim Days(20) As String
' Resize an Array using the ReDim Statement
ReDim Days(6)
Days(0) = "Sunday"
Days(1) = "Monday"
Days(2) = "Tuesday"
Days(3) = "Wednesday"
Days(4) = "Thursday"
Days(5) = "Friday"
Days(6) = "Saturday"

For i As Integer = 0 To Days.Length - 1


Console.WriteLine("Days Name in [{0}] index is {1}", i, Days(i))
Next

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module
Output:

Adding New Element to an Array


When we want to insert some new elements into an array of fixed size that is already filled with old array elements. So, in
this case, we can use a dynamic array to add new elements to the existing array.
Let us create a program to understand how we can add new elements to a dynamic array.
Dynamic_Arr1.vb
Imports System
Module Dynamic_arr1
Sub Main()
'Declaration and Initialization of String Array Days()
Dim Days() As String
' Resize an Array using the ReDim Statement
ReDim Days(2)
Days(0) = "Sunday"
Days(1) = "Monday"
Days(2) = "Tuesday"

Console.WriteLine(" Before Preserving the Elements")

35
For i As Integer = 0 To Days.Length - 1
Console.WriteLine("Days Name in [{0}] index is {1}", i, Days(i))
Next

Console.WriteLine(" After Preserving 0 to 2 index Elements")


ReDim Preserve Days(6)
Days(3) = "Wednesday"
Days(4) = "Thursday"
Days(5) = "Friday"
Days(6) = "Saturday"

For i As Integer = 0 To Days.Length - 1


Console.WriteLine("Days Name in [{0}] index is {1}", i, Days(i))
Next
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:

Program 1 :WAP to print marks and calculate grand total


Program 2 : WAP to print marks and grand total of a student which is given by user.

Structure

Structure is a user-defined datatype in computer language which allows us to combine data of different types together.
Structure helps to construct a complex data type which is more meaningful. It is somewhat similar to an Array, but an
array holds data of similar type only. But structure on the other hand, can store data of any type, which is practical more
useful.
For example: If I have to write a program to store Student information, which will have Student's name, age, branch,
permanent address, father's name etc, which included string values, integer values etc, how can I use arrays for this
problem, I will require something which can hold data of different types together.
In structure, data is stored in form of records.

in visual basic, Structures are same as classes but the only difference is classes are the reference types and structures are
the value types. As a value type, the structures directly contain their value so their object or instance will be stored on the
stack and structures are faster than classes.

In visual basic, the structures can contain fields, properties, member functions, operators, constructors, events,
indexers, constants and even other structure types.
Create Structures in Visual Basic
In visual basic, structures are declared by using Structure keyword. Following is the declaration of structure in a visual
36
basic programming language.

Public Structure Users


' Properties, Methods, Events, etc.
End Structure
If you observe the above syntax, we defined a structure “users” using Structure keyword with Public access modifier.
Here, the Public access specifier will allow the users to create an object for this structure and inside of the body structure,
we can create required fields, properties, methods and events to use it in our applications.

Following is the example of defining the structure in visual basic programming language.

Public Structure User


Public name As String
Public location As String
Public age As Integer
End Structure
If you observe the above example, we defined a structure called “User” with the required fields and we can add required
methods and properties based on our requirements.
Visual Basic Structure Initialization
In visual basic, structures can be instantiated with or without New keyword. Following is the example of assigning a
values to the variables of structure.

Dim u As User = New User()


u.name = "Suresh Dasari"
u.location = "Hyderabad"
u.age = 32
To make use of fields, methods and events of structure, it’s mandatory to instantiate the structure with New keyword in a
visual basic programming language.
Visual Basic Structure with Constructor
In visual basic, the structures won’t allow us to declare default constructor or constructor without parameters and it won’t
allow us to initialize the fields with values unless they are declared as const or shared.

Following is the example of defining the structure with parameterized constructor and initializing the fields in
a constructor in visual basic programming language.

Public Structure User


Public name, location As String
' Parameterized Constructor
Public Sub New(ByVal a As String, ByVal b As String)
name = a
location = b
End Sub
End Structure
If you observe the above example, we defined the structure called “User” with required fields and parameterized
constructor.

Structure with Default Constructor

As discussed, the structures will allow only parameterized constructors and fields cannot be initialized unless they are
declared it as const or shared.

Following is the example of defining the structure with a default constructor and initializing fields with values.

Structure User
' Compiler Error
37
Public name As String = "Suresh Dasari"
Public location As String
Public age As Integer
' Compiler Error
Public Sub New()
location = "Hyderabad"
age = 32
End Sub
End Structure
When we execute the above code, we will get a compile-time error because we declared a structure with the default
constructor (parameterless) and initialized fields without defining it as const or shared.

Now, we will see how to create a structure with fields and parameterized constructor in a visual basic programming
language with example.
Visual Basic Structure Example
Following is the example of creating the structure with a different type of fields and parameterized constructor in a visual
basic programming language with various data members and member functions.

Module Module1
Structure User
Public Const name As String = "Suresh Dasari"
Public location As String
Public age As Integer
Public Sub New(ByVal a As String, ByVal b As Integer)
location = a
age = b
End Sub
End Structure
Sub Main()
' Declare object with new keyword
Dim u As User = New User("Hyderabad", 31)
' Declare object without new keyword
Dim u1 As User
Console.WriteLine("Name: {0}, Location: {1}, Age: {2}", User.name, u.location, u.age)
' Initialize Fields
u1.location = "Guntur"
u1.age = 32
Console.WriteLine("Name: {0}, Location: {1}, Age: {2}", User.name, u1.location, u1.age)
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above example, we defined a structure (User) by including the required fields, parameterized
constructor and created an instance of structure (User) with and without New keyword to initialize or get the field values
based on our requirements.

VB.NET Enum
In VB.NET, Enum is a keyword known as Enumeration.
Enumeration is a user-defined data type used to define a related set of constants as a list using the
keyword enum statement. It can be used with module, structure, class, and procedure. For example, month names can be
grouped using Enumeration.
Syntax:
Enum enumeration name [ As Data type ]
' enumeration data_list or Enum member list
End Enum
38
In the above syntax, the enumeration name is a valid identifier name, and the data type can be mentioned if necessary, the
enumeration data_list or Enum member list represents the set of the related constant member of the Enumeration.
Declaration of Enumerated Data
Following is the declaration of enumerated data using the Enum keyword in VB.NET Programming language:
Enum Fruits
Banana
Mango
Orange
Pineapple
Apple
End Enum
Here, Fruits is the name of enumerated data that contains a list of fruits called enumeration lists.
When we are creating an Enumerator constant data list, by default, it assigns a value 0 to the first index of the enumerator.
Each successive item in the enumerator list is increased by 1. For example, in the above enumerator list, Banana value is 0,
Mango value is 1, Orange value is 2, and so on.
Moreover, if we want to assign a new value to the default value of the enumerator items, set a new value to the list's first
index, and then enumerator's values can automatically provide a new incremental value for successor objects in the
enumerator list.
Override a default index value by setting a new value for the first element of the enumerator list.
Enum Fruits
Banana = 5
Mango
Orange
Pineapple
Apple
End Enum
Here, we have assigned 5 as the new index value of the first item in an enumerator list. So, the initial value of the list's
Banana=5, Mango=6, orange=7, and so on. Furthermore, we can also provide new value in the middle of the enumerator
list, and then it follows the sequence set by the previous item.
Example 1: Write a program to understand the uses of enumeration data in VB.NET.
Enum_Data.vb
Imports System
Module Enum_Data
Enum Number
' List of enumerated data
One
Two
Three
Four
Five
Six
End Enum
Sub Main()
Console.WriteLine(" Without the index number")
Console.WriteLine(" Number {0}", Number.One) 'call with enumeration and items name
Console.WriteLine(" Number {0}", Number.Two)
Console.WriteLine(" Number {0}", Number.Three)
Console.WriteLine(" Number {0}", Number.Four)
Console.WriteLine(" Number {0}", Number.Five)
Console.WriteLine(" Number {0}", Number.Six)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Output:
39
In the above example, an enumerator "Number" that gets each value of the enumerated data such as "Number.One", etc. to
print the list.
Enum_month.vb
Imports System
Module Enum_month
Enum Monthname 'Enumeration name
January = 1
February
march
April
May
June
July
August
September = 10 'Set value to 10
October
November
December
End Enum
Sub Main()
Dim x As Integer = CInt(Monthname.June)
Dim y As Integer = CInt(Monthname.August)
Dim p As Integer = CInt(Monthname.September)
Dim q As Integer = CInt(Monthname.October)
Dim r As Integer = CInt(Monthname.December)

Console.WriteLine(" Month name is {0}", Monthname.January)


Console.WriteLine(" Index number is " & Monthname.January)
Console.WriteLine(" June Month name is in {0}", x & " Position")
Console.WriteLine(" August Month name is in {0}", y & vbCrLf & "Position")

Console.WriteLine(" After Setting a new value at the middle")


Console.WriteLine(" September Month name is {0}", p & " Position")
Console.WriteLine(" October Month name is {0}", q & " Position")
Console.WriteLine(" December Month name is {0}", r & " Position")
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()

End Sub
End Module

Procedure

A procedure is a group of statements that together perform a task when called. After the procedure is executed, the control
returns to the statement calling the procedure. VB.Net has two types of procedures −
40
Functions
Sub procedures or Subs
Functions return a value, whereas Subs do not return a value.

Functions

In VB.NET, the function is a separate group of codes that are used to perform a specific task when the defined function is
called in a program. After the execution of a function, control transfer to the main() method for further execution.
It returns a value. In vb.net, we can create more than one function in a program to perform various functionalities. The
function is also useful to code reusability by reducing the duplicity of the code. For example, if we need to use the same
functionality at multiple places in a program, we can simply create a function and call it whenever required.
Defining a Function
The syntax to define a function is:
[Access_specifier ] Function Function_Name [ (ParameterList) ] As Return_Type
[ Block of Statement ]
Return return_val
End Function
Where,
Access_Specifier: It defines the access level of the function such as public, private, or friend, Protected function to access
the method.
Function_Name: The function_name indicate the name of the function that should be unique.
ParameterList: It defines the list of the parameters to send or retrieve data from a method.
Return_Type: It defines the data type of the variable that returns by the function.
Public Function GetData( ByVal username As String, ByVal userId As Integer) As String
' Statement to be executed
End Function

Example: Write a program to reverse a number and check whether the given number is palindrome or not.
Palindrome.vb
Imports System
Module Palindrome
' Define a reverse() function
Function reverse(ByVal num As Integer) As Integer
' Define the local variable
Dim remain As Integer
Dim rev As Integer = 0
While (num > 0)
remain = num Mod 10
rev = rev * 10 + remain
num = num / 10
End While
Return rev
End Function
Sub Main()
' Define the local variable as integer
Dim n, num2 As Integer
Console.WriteLine(" Enter a number")
n = Console.ReadLine() 'Accept the number
num2 = reverse(n) ' call a function
Console.WriteLine(" Reverse of {0} is {1}", n, num2)

If (n = reverse(n)) Then
Console.WriteLine(" Number is a Palindrome")
Else
Console.WriteLine(" Number is not a Palindrome")
End If
41
Console.WriteLine("Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Sub
A Sub procedure is a separate set of codes that are used in VB.NET programming to execute a specific task, and it does
not return any values. The Sub procedure is enclosed by the Sub and End Sub statement. The Sub procedure is similar to
the function procedure for executing a specific task except that it does not return any value, while the function procedure
returns a value.

Defining the Sub procedure


Following is the syntax of the Sub procedure:
[Access_Specifier ] Sub Sub_name [ (parameterList) ]
[ Block of Statement to be executed ]
End Sub
Where,
Access_Specifier: It defines the access level of the procedure such as public, private or friend, Protected, etc. and
information about the overloading, overriding, shadowing to access the method.
Sub_name: The Sub_name indicates the name of the Sub that should be unique.
ParameterList: It defines the list of the parameters to send or retrieve data from a method.
Public Function GetData1( ByRef username As String, ByRef userId As Integer)
' Statement to be executed
End Sub

In the VB.NET programming language, we can pass parameters in two different ways:
Passing parameter by Value
Passing parameter by Reference
Passing parameter by Value
In the VB.NET, passing parameter by value is the default mechanism to pass a value in the Sub method. When the method
is called, it simply copies the actual value of an argument into the formal method of Sub procedure for creating a new
storage location for each parameter. Therefore, the changes made to the main function's actual parameter that do not affect
the Sub procedure's formal argument.
Syntax:
Sub Sub_method( ByVal parameter_name As datatype )
[ Statement to be executed]
End Sub
In the above syntax, the ByVal is used to declare parameters in a Sub procedure.
Let's create a program to understand the concept of passing parameter by value.
Passing_value.vb
Imports System
Module Passing_value
Sub Main()
' declaration of local variable
Dim num1, num2 As Integer
Console.WriteLine(" Enter the First number")
num1 = Console.ReadLine()
Console.WriteLine(" Enter the Second number")
num2 = Console.ReadLine()
Console.WriteLine(" Before swapping the value of 'num1' is {0}", num1)
Console.WriteLine(" Before swapping the value of 'num2' is {0}", num2)
42
Console.WriteLine()

'Call a function to pass the parameter for swapping the numbers.


swap_value(num1, num2)
Console.WriteLine(" After swapping the value of 'num1' is {0}", num1)
Console.WriteLine(" After swapping the value of 'num2' is {0}", num2)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub

' Create a swap_value() method


Sub swap_value(ByVal a As Integer, ByVal b As Integer)
' Declare a temp variable
Dim temp As Integer
temp = a ' save the value of a to temp
b = a ' put the value of b into a
b = temp ' put the value of temp into b
End Sub
End Module

Passing parameter by Reference


A Reference parameter is a reference of a variable in the memory location. The reference parameter is used to pass a
reference of a variable with ByRef in the Sub procedure. When we pass a reference parameter, it does not create a new
storage location for the sub method's formal parameter. Furthermore, the reference parameters represent the same memory
location as the actual parameters supplied to the method. So, when we changed the value of the formal parameter, the
actual parameter value is automatically changed in the memory.The syntax for the passing parameter by Reference:
Sub Sub_method( ByRef parameter_name, ByRef Parameter_name2 )
[ Statement to be executed]
End Sub
In the above syntax, the ByRef keyword is used to pass the Sub procedure's reference parameters.
Let's create a program to swap the values of two variables using the ByRef keyword. Passing_ByRef.vb
Imports System
Module Passing_ByRef
Sub Main()
' declaration of local variable
Dim num1, num2 As Integer
Console.WriteLine(" Enter the First number")
num1 = Console.ReadLine()
Console.WriteLine(" Enter the Second number")
num2 = Console.ReadLine()
Console.WriteLine(" Before swapping the value of 'num1' is {0}", num1)
Console.WriteLine(" Before swapping the value of 'num2' is {0}", num2)
Console.WriteLine()

'Call a function to pass the parameter for swapping the numbers.


swap_Ref(num1, num2)
Console.WriteLine(" After swapping the value of 'num1' is {0}", num1)
Console.WriteLine(" After swapping the value of 'num2' is {0}", num2)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub

' Create a swap_Ref() method


Sub swap_Ref(ByRef a As Integer, ByRef b As Integer)
' Declare a temp variable
Dim temp As Integer
43
temp = a ' save the value of a to temp
a = b ' put the value of b into a
b = temp ' put the value of temp into b
End Sub
End Module

44
UNIT 3

45
UNIT III

VB.NET MDI Form

MDI stands for Multiple Document Interface applications that allow users to work with multiple documents by opening
more than one document at a time. Whereas, a Single Document Interface (SDI) application can manipulate only one
document at a time.
The MDI applications act as the parent and child relationship in a form. A parent form is a container that contains child
forms, while child forms can be multiple to display different modules in a parent form.
VB.NET has folowing rules for creating a form as an MDI form.
MidParent: The MidParent property is used to set a parent form to a child form.
ActiveMdiChild: The ActiveMdiChild property is used to get the reference of the current child form.
IsMdiContainer: The IsMdiContainer property set a Boolean value to True that represents the creation of a form as an
MDI form.
LayoutMdi(): The LayoutMdi() method is used to arrange the child forms in the parent or main form.
Controls: It is used to get the reference of control from the child form.
Let's create a program to display the multiple windows in the VB.NET

Windows Forms.

Step 1: First, we have to open the Windows


form and create the Menu bar with the use of MenuStrip control, as shown below.

Step 2: After creating the Menu, add the Subitems into the Menu bar, as shown below.

46
Hear we have defined two Subitems, First is the Feedback Form, and the Second is VB.NET.
Step 3: In the third step, we will create two Forms: The Child Form of the Main Form or Parent Form.
Here, we have created the first Child Form with the name Form2.
Form2.vb

Public Class Form2


Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Feedback form" ' Set the title of the form
Label1.Text = " Fill the Feedback form"
Button1.Text = "Submit"
Button1.BackColor = Color.SkyBlue
Button2.Text = "Cancel"
Button2.BackColor = Color.Red
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox(" Successfully submit the feedback form")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Dispose() ' end the form2
End Sub
End Class
Another Child Form with the name Form3.
Form3.vb
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Text = "Welcome to Disha College"
Label.BackColor = Color.Green
Label2.Text = "This is the VB.NET Tutorial and we are learning the VB.NET MDI Form"
Label2.BackColor = Color.SkyBlue
End Sub
End Class
Step 4: Now we write the programming code for the Main or Parent Form, and here is the code for our Main Form.
MDI_form.vb
Public Class MDI_Form
Private Sub MDI_Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
47
IsMdiContainer = True 'Set the Boolean value to true to create the form as an MDI form.
Me.Text = "BCA-3" 'set the title of the form
PictureBox1.Image = Image.FromFile("C:\Users\Dessktop\Imagename.png")
PictureBox1.Height = 550
PictureBox1.Width = 750
End Sub
Private Sub FeedbackFormToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FeedbackFormToolS
tripMenuItem.Click
PictureBox1.Visible = False
Dim fm2 As New Form2
fm2.MdiParent = Me 'define the parent of form3, where Me represents the same form
fm2.Show() 'Display the form3
End Sub
Private Sub VBNETToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VBNETToolStripMenuIte
m.Click
PictureBox1.Visible = False
Dim fm3 As New Form3
fm3.MdiParent = Me 'define the parent of form3, where Me represent the same form
fm3.Show() 'Display the form3
End Sub
End Class

MsgBox and InputBox


MsgBox ( ) Function
The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a command button before he
/she can continues. This format is as follows:
yourMsg=MsgBox(Prompt, Style Value, Title)
The first argument, Prompt, will display the message in the message box. The Style Value will determine what type of
command buttons appear on the message box, please refer to Table 12.1 for types of command button displayed. The Title
argument will display the title of the message board.
Style Value Named Constant Buttons Displayed
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons
We can use named constants in place of integers for the second argument to make the programs more readable. For
example:
yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu")
and
yourMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup Menu")
are the same.
yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The values are determined by the
type of buttons being clicked by the users. It has to be declared as Integer data type in the procedure or in the general
declaration section. Table 1 shows the values, the corresponding named constant and buttons.
Table : Return Values and Command Buttons
Value Named Constant Button Clicked
1 vbOk Ok button
2 vbCancel Cancel button
48
3 vbAbort Abort button
4 vbRetry Retry button
5 vbIgnore Ignore button
6 vbYes Yes button
7 vbNo No button
Example
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
MessageBox.Show("You have clicked the OK button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub
To make the message box looks more sophisticated, you can add an icon besides the message. There are four types of
icons available -
Types of Icons
Value Named Constant Icon

16 vbCritical

3 vbQuestion

48 vbExclamation

64 vbInformation

Example
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim testMsg As Integer
testMsg = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message")
If testMsg = 6 Then
MessageBox.Show("You have clicked the yes button")
ElseIf testMsg = 7 Then
MessageBox.Show("You have clicked the NO button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub

49
Figure -The MessageBox
The InputBox( ) Function
An InputBox( ) function will display a message box where the user can enter a value or a message in the form of text. ,
you can use the following format:
myMessage=InputBox(Prompt, Title, default_text, x-position, y-position)
myMessage is a variant data type but typically it is declared as string, which accept the message input by the users. The
arguments are explained as follows:
Prompt - the message displayed normally as a question asked.
Title - The title of the Input Box.
default-text - The default text that appears in the input field where users can use it as his intended input or he may change
to the message he wish to enter.
x-position and y-position - the position or tthe coordinates of the input box.
However, the format won't work in Visual Basic 2012 because InputBox is considered a namespace. So, you need to key
in the full reference to the Inputbox namespace, which is
Microsoft.VisualBasic.InputBox(Prompt, Title, default_text, x-position, y-position)
The parameters remain the same.
Example
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim userMsg As String
userMsg = Microsoft.VisualBasic.InputBox("What is your message?", "Message Entry Form", "Enter your
messge here", 500, 700)
If userMsg <> "" Then
MessageBox.Show(userMsg)
Else
MessageBox.Show("No Message")
End If
End Sub
The input box will appear as shown in the figure below when you press the command button

VB.NET Form Controls


VB.NET Form Properties
The following are the most important list of properties related to a form. And these properties can be set or read while the
application is being executed.

50
Properties Description

51
BackColor It is used to set the background color for the form.

BackgroundImag It is used to set the background image of the form.


e

Cursor It is used to set the cursor image when it hovers over the form.

AllowDrop Using the AllowDrop control in a form, it allows whether to drag and drop on the
form.

Font It is used to get or set the font used in a form.

Locked It determines whether the form is locked or not.

FormBorderStyle It is used to set or get border style in a form.

Text It is used to set the title for a form window.

MinimizeBox MinimizeBox It is used to display the minimum option on the title bar of the
form.

IsMDIChild It is used to authenticate whether a form is a container of a Multiple Document


Interface (MDI) child form.

Autoscroll It allows whether to enable auto-scrolling in a form.

MaximizeBox It is used to display the maximum option on the title bar of the form.

MaximumSize It is used to set the maximum height and width of the form.

Language It is used to specifies the localized language in a form.

AcceptButton It is used to set the form button if the enter key is pressed.

Top, Left It is used to set the top-left corner coordinates of the form in pixel.

Name It is used to define the name of the form.

MinimumSize It is used to set the minimum height and width of the form.

Enabled It uses the True or False value to enable mouse or keyboard events in the form.

TopMost It uses a Boolean value that represents whether you want to put the window form
on top of the other form. By default, it is False.
Form Events
Events Description

Activated An activated event is found when the user or program activates the form.

Click A click event is active when the form is clicked.

Closed A closed event is found before closing the form.

Closing It exists when a form is closing.

DoubleClick DoubleClick
The DoubleClick event is activated when a user double clicks on the form.

52
DragDrop A DragDrop event is activated when a drag and drop operation is performed.

MouseDown A MouseDown event is activated when the mouse pointer is on the form, and
the mouse button is pressed.

GotFocus A GotFocus event is activated when the form control receives a focus.

HelpButtonClicke It is activated when a user clicked on the help button.


d

KeyDown A KeyDown event is activated when a key is pressed while focussing on the
form.

KeyUp A KeyUp event is activated when a key is released while focusing on the form.

Load The load event is used to load a form before it is first displayed.

LostFocus It is activated when the form loses focus.

MouseEnter A MouseEnter event is activated when the mouse pointer enters the form.

MouseHover A MouseHover event is activated when the mouse pointer put on the form.

MouseLeave A MouseLeave event is activated when the mouse pointer leaves the form
surface.

Shown It is activated whenever the form is displayed for the first time.

Scroll A Scroll event is activated when a form is scrolled through a user or code.

Resize A Resize event is activated when a form is resized.

Move A Move event is activated when a form is moved.

For creating a Windows Forms application in VB.NET, we need to follow the following steps in Microsoft Visual Studio.
GoTo File Menu.
Click on New Project.
Click on Windows Forms App or Application
And finally, click on the 'Create' button to create your project, and then, it displays the following window form with a
name Form1.

53
After filling all the details, click on the Submit button. After that, it will shows the Output:
VB.NET Label Control
Step 1: We have to drag the Label control from the Toolbox and drop it on the Windows form, as shown below.

54
Step 2: Once the Label is added to the form, we can set various properties to the Label by clicking on the Label control.
Public Class Label
Private Sub Label_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Disha College" 'Set the title for a Windows Form
Label1.Text = "Student Registration"
Label1.Font = New Font("Microsoft Sans Serif", "style = Bold", "Italic", 18) ' Set Font style
Label2.Text = "Student Name"
Label2.Font = New Font("Microsoft Sans Serif", "style = Bold", "Italic", 12)
Label3.Text = "Father's Name"
Label3.Font = New Font("Microsoft Sans Serif", "style = Bold", "Italic", 12)
Label4.Text = "Course "
Label4.Font = New Font("Microsoft Sans Serif", "style = Bold", "Italic", 12)
Label5.Text = "Address"
Label5.Font = New Font("Microsoft Sans Serif", "style = Bold", "Italic", 12)
Button1.Text = "Send"
TextBox1.Text = " "
TextBox2.Text = " "
TextBox3.Text = " "
RichTextBox1.Text = " "
End Sub
End Class

VB.NET Label Properties


Properties Description

AutoSize As the name defines, an AutoSize property of label control is used to set or get a
value if it is automatically resized to display all its contents.

Border Style It is used to set the style of the border in the Windows form.

PreferredWidth It is used to set or get the preferred width for the Label control.

Font It is used to get or set the font of the text displayed on a Windows form.

55
PreferredHeight It is used to set the height for the Label Control.

TextAlign It is used to set the alignment of text such as centre, bottom, top, left, or right.

ForeColor It is used to set the color of the text.

Text It is used to set the name of a label in the Windows Form.

ContextMenu It is used to get or sets the shortcut menu associated with the Label control.

DefaultSize It is used to get the default size of the Label control.

Image It is used to set the image to a label in Windows Form.

ImageIndex It is used to set the index value to a label control displayed on the Windows form.

VB.NET Label Events


Events Description

AutoSizeChanged An AutoSizeChanged event occurs in the Label control when the value of
AutoSize property is changed.

Click Click event is occurring in the Label Control to perform a click.

DoubleClick When a user performs a double-clicked in the Label control, the DoubleClick
event occurs.

GotFocus It occurs when the Label Control receives focus on the Window Form.

Leave The Leave event is found when the input focus leaves the Label Control.

TabIndexChanged It occurs when the value of Tabindex property is changed in the Label control.

ControlRemoved When the control is removed from the Control.ControlCollection, a


ControlRemoved event, occurs.

TabStopChanged It occurs when the property of TabStop is changed in the Label Control.

BackColorChange A BackColorChanged event occurs in the Label control when the value of the
d BackColor property is changed.

ControlAdded When a new control is added to the Control.ControlCollection, a ControlAdded


event occurs.

DragDrop A DragDrop event occurs in the Label control when a drag and drop operation
is completed.

VB.NET Button Properties

Properties Description

AutoSizeMode It is used to get or set the auto mode value through which the button can
automatically resize in the Windows form.
56
BackColor It is used to set the background color of the Button in the Windows form.

BackgroundImag It is used to set the background image of the button control.


e

ForeColor It is used to set or get the foreground color of the button control.

Image It is used to set or gets the image on the button control that is displayed.

Location It is used to set the upper-left of the button control's coordinates relative to the
upper-left corner in the windows form.

Text It is used to set the name of the button control in the windows form.

AllowDrop It is used to set or get a value representing whether the button control can accept
data that can be dragged by the user on the form.

TabIndex It is used to set or get the tab order of the button control within the form.

VB.NET Button Events


BackColorChanged A BackColorChaged event is found in button control when the
Background property is changed.

BackgroundImageChange A BackgoundImageChanged event is found in button control when the


d value of the BackgoundImage property is changed.

Click A Click event is found in the button control when the control is clicked.

ContextManuChanged It is found in button control when the value of the ContextMenu


property is changed.

ControlAdded A ControlAdded event is found in button control when a new control is


added to the Control.ControlCollection.

CursorChanged A CursorChanged event is found in button control when the value of the
control is changed.

DoubleClick When the user makes a double click on the button, a double click event
is found in the button control.

TextChanged It is found in the button control when the value of the text property is
changed.

DragDrop The DragDrop event is found in the button control when the drag and
drop operation is completed in the Form.
Button_Control.vb

Public Class Button_Control


Private Sub Button_Control_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Button1.Text = "Click Me" ' Set the name of button
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


MsgBox(" Visit here: https://www.javatpoint.com")
' Display the message, when a user clicks on Click me button
End Sub
End Class
57
VB.NET TextBox Properties
the font style of the text
displayed on a Windows form.

Lines It is used to set the number of lines in a TextBox control.

CharacterCasing It is used to get or set a value representing whether the TextBox


control can modify the character's case as they typed.

Multiline It is used to enter more than one line in a TextBox control, by


changing the Multiline property value from False to True.

AcceptsReturn It is used to get or set a value that indicates whether pressing the
enter button in a multiline textbox; it creates a new line of text in
control.

PasswordChar It is used to set the password character that can be a mask in a


single line of a TextBox control.

PreferredHeight It is used to set the preferred height of the textbox control in the
window form.

ScrollBars It is used to display a scrollbar on a multiline textbox by setting a


value for a Textbox control.

Text It is used to get or set the text associated with the textbox control.

Visible The Visible property sets a value that indicates whether the textbox
should be displayed on a Windows Form.

WordWrap The WordWrap properties validate whether the multiline Textbox


control automatically wraps words to the beginning of the next line
when necessary.

VB.NET TextBox Events

Events Description

Click When a textbox is clicked, a click event is called in the textbox control.

CausesValidationChange It occurs in the TextBox Control when the value of CauseValidation


d property is changed.

AcceptTabsChanged It is found in the TextBox control when the property value of the
AcceptTab is changed.

BackColorChanged It is found in the TextBox Control when the property value of the
BackColor is changed.

BorderStyleChanged It is found in the TextBox Control when the value of the BorderStyle is
changed.

ControlAdded It is found when the new control is added to the


Control.ControlCollection.

CursorChanged It is found in TextBox, when the textbox control is removed from the
58
Control.ControlCollection.

FontChanged It occurs when the property of the Font is changed.

GetFocus It is found in TextBox control to get the focus.

MouseClick A MouseClick event occurs when the mouse clicks the control.

MultilineChanged It is found in a textbox control when the value of multiline changes.

Public Class class1


Private Sub form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Disha College" ' title name
Label1.Text = "User Login Details" ' Set the title name for Label1
Label2.Text = "Name" ' Set the name for label2
Label3.Text = "Username" ' Set the username for label2
Label4.Text = "Password" ' Set the label name Passowrd
Text3.PasswordChar = "*"
Button1.Text = "Login" ' Set the name of Button1 as Login
Button2.Text = "Exit" ' Set the name of Button2 As Exit
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click


End ' terminate the program when the user clinks button 2
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


Dim name As String
Dim Uname As String
Dim pass As String
name = text1.Text
Uname = Text2.Text
pass = Text3.Text
' Display the user details, when the Button1 is clicked
MsgBox(" Your Name: " & name + vbCrLf + "Your UserName: " & Uname + vbCrLf + "Your Password: " & pass)
End Sub
End Class
RichTextBox Control

The RichTextBox control provides properties for manipulating the selected text on the control.
Property What It Manipulates
SelectedText The selected text
SelectedRtf The RTF code of the selected text
SelectionStart The position of the selected text’s first character
SelectionLength The length of the selected text
SelectionFont The font of the selected text
SelectionColor The color of the selected text
SelectionBackColor The background color of the selected text
SelectionAlignment The alignment of the selected text

59
Property What It Manipulates
SelectionIndent, The indentation of the selected text
SelectionRightIndent,
SelectionHangingIndent
RightMargin The distance of the text’s right margin from the
left edge of the control
SelectionTabs An array of integers that sets the tab stop
positions in the control
SelectionBullet Whether the selected text is bulleted
BulletIndent The amount of bullet indent for the selected text
Program:

Public Class Form1


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'Find method is used to find the text written in RichTextBox


RichTextBox1.SelectionStart = RichTextBox1.Find('Hello')
RichTextBox1.SelectionColor = Color.BlueViolet
RichTextBox1.SelectionStart = RichTextBox1.Find('How are you')
RichTextBox1.SelectionColor = Color.DarkOliveGreen

End Sub
End Class

Program to Save RichTextBox Text in File


Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' SaveFile Method Saves the contents of the RichTextBox to a file.
RichTextBox1.SaveFile('hello.rtf')
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'LoadFile Method Loads the contents of a file into the RichTextBox control.
RichTextBox2.LoadFile('hello.rtf')
End Sub
60
RadioButton Control

The RadioButton is used to select one option from the number of choices. If we want to select only one item from a related
or group of items in the windows forms,
Property Description

AllowDrop It is used to set or get a value representing whether the RadioButton allows the
user to drag on the form.

Appearance It is used to get or set a value that represents the appearance of the RadioButton.

AutoScrollOffset It is used to get or set the radio control in ScrollControlIntoView(Control).

AutoCheck The AutoCheck property is used to check whether the checked value or
appearance of control can be automatically changed when the user clicked on the
RadioButton control.

AutoSize The AutoSize property is used to check whether the radio control can be
automatically resized by setting a value in the RadioButton control.

CanSelect A CanSelect property is used to validate whether a radio control can be selected by
setting a value in the RadioButton control.

CheckAlign It is used to obtain or set a value that indicates the location of the check portion in
the radioButton control.

Text The Text property is used to set the name of the RadioButton control.
RadioButton Methods
Method Name Description

Contains(Control) The Contains() method is used to check if the defined control is available in
the RadioButton control.

DefWndProc(Message) It is used to send the specified message to the Window procedure.

DestroHandle() It is used to destroy the handle associated with the RadioButton Control.
61
Focus() The Focus() method is used to set the input focus to the window form's
RadioButton control.

GetAutoSizeMode() It is used to return a value that represents how the control will operate when
the AutoSize property is enabled in the RadioButton control of the Window
form.

ResetText() As the name suggests, a ResetText() method is used to reset the property of
text to its default value or empty.

Update() It is used to reroute an invalid field, which causes control in the client
region.

We can also refer to Microsoft documentation to get a complete list of RadioButton Control properties and methods in the
VB .NET.
Let's create a program to understand the uses of Radio button control in the VB.NET form.

RadioBtn.vb
Public Class RadioBtn
Private Sub RadioBtn_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Disha College" ' Set the title of the form
Label1.Text = "Select the Gender"
RadioButton1.Text = "Male" ' Set the radiobutton1 and radiobutton2
RadioButton2.Text = "Female"
RadioButton3.Text = "Transgender"
Button1.Text = "Submit" ' Set the button name
Button2.Text = "Exit"
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


Dim gen As String
If RadioButton1.Checked = True Then
gen = "Male"
MsgBox(" Your gender is : " & gen)

ElseIf RadioButton2.Checked = True Then


gen = "Female"
MsgBox(" Your gender is : " & gen)
Else
gen = "Transgender"
MsgBox(" You have Selected the gender : " & gen)
End If

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click


End 'Terminate the program
End Sub
End Class
CheckBox Control
The CheckBox control is a control that allows the user to select or deselect options from the available options. When a
checkbox is selected, a tick or checkmark will appear on the Windows form.

62
Property Description

Default It is used to get the default size of the checkbox.

AutoCheck The AutoCheck property is used to check whether the checked value or appearance of
control can be automatically changed when the user clicked on the CheckBox control.

CheckAlig It is used to set the checkmark's alignment, such as horizontal or vertical on the
n checkbox.

Appearance The Appearance property is used to display the appearance of a checkbox control by
setting a value.

CheckState The CheckState property is used to verify whether the checkbox status is checked in the
window form.

ThreeState The ThreeState property is used to check whether the control allows one to set three
check positions instead of two by setting values.

FlatStyle It is used to obtain or set the flat appearance of a checkbox.

CheckBox Methods

There are some Methods of the VB.NET CheckBox control.


Method Description

OnClick The OnClick method is used to fetch the Click event in the CheckBox
control.

OnCheckStateChanged It is used to call the CheckStateChanged event in the CheckBox control.

ToString The ToString method is used to return the current string of the CheckBox
control.

OnCheckedChanged When the Checked property is changed in the CheckBox control, the
OnCheckedChanged events occur.

OnMouseUp It is used when it receives the OnMouseUp event in the CheckBox control.
CheckBox Events
There are some Events of the VB.NET CheckBox control.
Event Description

CheckedChanged The CheckedChanged event is found when the value of the checked property is
changed to CheckBox.
63
DoubleClick It occurs when the user performs a double click on the CheckBox control.

CheckStateChanged It occurs when the value of the CheckState property changes to the CheckBox
control.

AppearanceChange It occurs when the property of the Appearance is changed to the CheckBox
d control.

Let's create a program to understand the uses of CheckBox control in the VB.NET form.
Checkbx.vb
Public Class Checkbxvb
Private Sub Checkbxvb_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Disha College" ' Set the title name of the form
Label1.Text = "Select the fruits name"
CheckBox1.Text = "Apple"
CheckBox2.Text = "Mango"
CheckBox3.Text = "Banana"
CheckBox4.Text = "Orange"
CheckBox5.Text = "Potato"
CheckBox6.Text = "Tomato"
Button1.Text = "Submit"
Button2.Text = "Close"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fruit As String
fruit = " "
If CheckBox1.Checked = True Then
fruit = "Apple"
End If
If CheckBox2.Checked = True Then
'fruit = CheckBox2.Text
fruit = fruit & " Mango"
End If
If CheckBox3.Checked = True Then
fruit = fruit & " Banana"
End If
If CheckBox4.Checked = True Then
fruit = fruit & " Orange"
End If
If CheckBox5.Checked = True Then
fruit = fruit & " Potato"
End If
If CheckBox6.Checked = True Then
fruit = fruit & " Tomato"
End If
If fruit.Length <> 0 Then
MsgBox(" Selected items " & fruit)
End If
CheckBox1.ThreeState = True
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
End 'terminate the program
End Sub
End Class
Panel Control in VB.Net
64
Collection of control can be placed in side Panel.

GroupBox Control

GroupBox is a container of other control. It displays a frame around a group of controls. When you move the
GroupBox control, all of its contained will also move.
How to use the GroupBox Control
Drag and drop GroupBox control from the toolbox on the window Form. When you drag and drop the group box, it has a
border by default,
and its caption is set to the name of the control. You can change its caption.

GroupBox is a container of other control.

65
GroupBox properties

AutoSize: Gets or sets a value that indicates whether the GroupBox resizes based on its contents.
BackColor: Gets or sets the background color for the control.
Panel is Scrollable whereas GroupBox isn't, and GroupBox has a caption, whereas a Panel doesn't.
Panel Vs GroupBox
Panel allows drop, GroupBox don't.
GroupBox always have property TabStop enabled, in Panel you can choose.

VB.NET ComboBox Control


The ComboBox control is used to display more than one item in a drop-down list. It is a combination
of Listbox and Textbox in which the user can input only one item.
Property Description

AllowSelection The AllowSelection property takes the value that indicates whether the list
allows selecting the list item.

AutoCompleteMode It takes a value that represents how automatic completion work for the
ComboBox.

Created It takes a value that determines whether the control is created or not.

DataBinding It is used to bind the data with a ComboBox Control.

BackColor The BackColor property is used to set the background color of the combo box
control.

DataSource It is used to get or set the data source for a ComboBox Control.

FlatStyle It is used to set the style or appearance for the ComboBox Control.

MaxDropDownItem The MaxDropDownItems property is used in the combo box control to display
s the maximum number of items by setting a value.

MaxLength It is used by the user to enter maximum characters in the editable area of the
combo box.

SelectedItem It is used to set or get the selected item in the ComboBox Control.

Sorted The Sorted property is used to sort all the items in the ComboBox by setting
66
the value.

ComboBox Events

Events Description

FontChanged It occurs when the property of the font value is changed.

Format When the data is bound with a combo box control, a format event is called.

SelectIndexChanged It occurs when the property value of SelectIndexChanged is changed.

HelpRequested When the user requests for help in control, the HelpRequested event is called.

Leave It occurs when the user leaves the focus on the ComboBox Control.

MarginChanged It occurs when the property of margin is changed in the ComboBox control.
Let's create a program to display the Calendar in the VB.NET

Windows Form

ComboBox_Control.vb
Public Class ComboBox_Control
Dim DT As Integer
Dim MM As String
Dim YY As Integer
Private Sub ComboBox_Control_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Disha College"
Label1.Text = "Display Calendar"
Label2.Text = "Get Date"
Button1.Text = "Date"
Button2.Text = "Exit"
ComboBox1.Items.Add("Date")
ComboBox1.Items.Add("01")
ComboBox1.Items.Add("02")
ComboBox1.Items.Add("03")
ComboBox1.Items.Add("04")
ComboBox1.Items.Add("05")
ComboBox1.Items.Add("06")
ComboBox1.Items.Add("07")
ComboBox1.Items.Add("08")
ComboBox1.Items.Add("09")
ComboBox2.Items.Add("Month")
ComboBox2.Items.Add("January")
ComboBox2.Items.Add("February")
ComboBox2.Items.Add("March")
ComboBox2.Items.Add("May")
ComboBox2.Items.Add("June")
ComboBox2.Items.Add("July")
ComboBox3.Items.Add("Year")
ComboBox3.Items.Add("2016")
ComboBox3.Items.Add("2017")
ComboBox3.Items.Add("2018")
ComboBox3.Items.Add("2019")
ComboBox3.Items.Add("2020")
67
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


DT = ComboBox1.Text
MM = ComboBox2.Text
YY = ComboBox3.Text
MsgBox("Month " & MM + vbCrLf + "Year " & YY)
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click


End
End Sub
End Class

ListBox Control

The ListBox control is used to display a list of items in Windows form. It allows the user to select one or more items from
the ListBox Control.
Properties Description
Name

AllowSelection It takes a value that defines whether the list box allows the user to select the item
from the list.

CanSelect It obtains a value that determines whether the Listbox control can be selected.

ColumnWidth It is used to get or set the width of the columns in a multicolumn Listbox.

Container As the name defines, a container gets the IContainer that stores the component of
ListBox control.

Controls It is used to get the collection of controls contained within the control.

Created It takes a value that determines whether the control is created or not.

Width It is used to set the width of the ListBox control.

Visible It takes a value that determines whether the ListBox control and all its child are
displayed on the Windows Form.

SelectionMode It is used to get or set the method that determines which items are selected in the
ListBox.

MultiColumn It allows multiple columns of the item to be displayed by setting the True value in
the Listbox.
ListBox Methods
Method Name Description

Add() The Add() method is used to add items to an item collection.

Remove It is used to remove an item from an item collection. However, we can remove
items using the item name.

Clear It is used to remove all items from the item collection at the same time.

Contains It is used to check whether the particular item exists in the ListBox or not.
68
Show() It is used to display the control to the user.

Sort() As the name suggests, a Sort() method is used to arrange or sort the elements in
the ListBox.

ResetText() A ResetText() method is used to reset ListBox's text property and set the default
value.

ResetBackColor() It is used to reset the backColor property of the ListBox and set the default value.

OnNotifyMessag It is used to notify the message of the ListBox to Windows.


e

GetSelected The GetSelected method is used to validate whether the specified item is selected.

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list of ListBox properties, and
methods.
Let's create a program to select an item from the ListBox in the VB.NET form.
Listbx.vb
Public Class Listbox
Private Sub Listbox_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' set the title of the Form.
Me.Text = "Disha College"
' Add the items into the ListBox
ListBox1.Items.Add("Earth")
ListBox1.Items.Add("Mercury")
ListBox1.Items.Add("Mars")
ListBox1.Items.Add("Jupiter")
ListBox1.Items.Add("Venus")
ListBox1.Items.Add("Neptune")
ListBox1.Items.Add("Uranus")
' Set the name of the Button1 and Button2
Button1.Text = "Show"
Button2.Text = "Exit"
Label2.Text = "Select the solar system from the ListBox"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lt As String ' define a local variable.
lt = ListBox1.Text 'accept the data from the ListBox1
MsgBox(" Selected Solar System is " & lt) ' Display the selected item
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChan
ged
Label1.Text = ListBox1.SelectedItem.ToString() 'When a user clicks on an item, it displays the item name.
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click


End 'End or exit an application
End Sub
End Class

CheckedListBox Control

The CheckedListBox is similar to Listbox except that it displays all items in the list with a checkbox that allows users to
check or uncheck single or multiple items.
69
Properties Description

AccessibilityObject It obtains a value that determines whether the AccessibilityObject is assigned


to the CheckedListBox control.

AccessibleName It gets or sets a value that tells if the accessible client application has used the
name of the checkedlistbox control.

AllowSelection It gets a value that indicates whether the ListBox allows for the item to be
selected from the list.

AllowScollOffset It gets or sets a value representing whether the CheckedListBox control is


scrolled in ScrollControlIntoView(Control).

BorderStyle It is used to set the type of border around the CheckedListBox by getting or
setting a value.

CheckedItems It is used to store a collection of checked items in the CheckedListBox.

ScrollAlwaysVisibl It is used to set or get a value that indicates if the vertical scroll bar appears in
e Windows Forms at all times.

SelectedItems It is used to get all selected items from CheckedListBox.

SelectionMode It is used to get or set a value representing the items' selection mode in the
CheckedListBox.

TopIndex It is used to set the first visible item at the top of the index in the
CheckedListBox.

CheckedListBox Methods

Methods Description

ClearSelected() It is used to unselect all the selected items in the CheckedListBox.

CreateAccessibilityInstance() It is used to create new accessibility of the object in the


CheckedListBox Control.

CreateItemCollection() It is used to create a new instance for the collected item in the list box.

DestroyHandle() It is used to destroy the handle associated with CheckedListBox.

Equals(Object) It is used to validate whether the specified object is equal to the


current object in the CheckedListBox or not.

FindForm() It is used to obtain the form in which CheckedListBox has control.

GetItemText(Object) It is used to get the text of the specified item in the CheckedListBox.

GetType() It is used to get the current item type in the CheckedListBox.

Show() A Show() method is used to display the CheckedListBox Control to


the user.

Sort() A Sort() method is used to sort or organize all the items available in
CheckedListBox.
70
Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list of CheckedListBox properties
and methods.

Program:
Public Class CheqListvb
Private Sub CheqListvb_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = " Disha College"
CheckedListBox1.Items.Add("VB.NET")
CheckedListBox1.Items.Add("Java")
CheckedListBox1.Items.Add("Python")
CheckedListBox1.Items.Add("C")
CheckedListBox1.Items.Add("C#")
CheckedListBox1.Items.Add("PHP")
CheckedListBox1.Items.Add("JavaScript")
CheckedListBox1.Items.Add("Ruby Language")
CheckedListBox1.Items.Add("Android")
CheckedListBox1.Items.Add("Perl")
Label1.Text = "Choose one or more programming languages of your choice. "
Button1.Text = "Select"
Button2.Text = "Exit"
End Sub

' To submit the checked items, click on Button1 or Select


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cheq As New System.Text.StringBuilder
For Each item In CheckedListBox1.CheckedItems
cheq.Append(item)
cheq.Append(" ")
Next
MessageBox.Show(" Your Checked Items are : " & cheq.ToString())

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click


End 'terminate the program
End Sub

PictureBox Control

PictureBox control is used to display the images on Windows Form. The PictureBox control has an image property that
allows the user to set the image at runtime or design time.
Property Description

BackColor It is used to set the background color for the PictureBox in the window form.

BackgroundImag It is used to set the background image of a window form by setting or getting
e value in the picture box.

ErrorImage The ErrorImage property is used to display an image if an error occurs while
loading an image on a window form.

InitialImage The initial image is used to display an image on the PictureBox when the main
image is loaded onto a window form by setting a value in the PictureBox control.

WaitOnLoad It represents whether the particular image is synchronized or not in the


71
PictureBox control.

Text It is used to set text for the picture box controls in the window form.

Image The image property is used to display the image on the PictureBox of a Windows
form.

BorderStyle It is used to set the border style for the picture box in the windows form.

ImageLocation It is used to set or get the path or URL of the image displayed on the picture box
of the window form.

IsMirrored It obtains a value that determines whether the picture box control is mirrored.

Methods of the PictureBox Control

Method Description

CancelAysnc() The CancelAsync method is used to cancel an asynchronous image load in a


PictureBox control.

CreateHandle() It is used to create handles for the picture box controls in window form.

DestroyHandle() It is used to destroy all the handles that are associated with the picture box
control.

GetStyle() The GetStyle() method is used to get values for the specified bit style in the
PictureBox control.

Load() The Load() method is used to load the specified image from the control using
the ImageLocation property.

LoadAsync(String It is used to asynchronous load the image at the specified position of the picture
) box control.

Events of the PictureBox Control

There are some Events of the VB.NET PictureBox control.


Events Description

BackColorChanged It occurs when the property of the backcolor is changed in the


PictureBox control.

BackgroundImageLayoutChange It occurs when the property value of the BackgroundImage is


d changed in the PictureBox control.

ContextMenuChanged It occurs when the property of the ContextMenu is changed in the


PictureBox control.

Resize The resize event occurs when the picture box control is changed.

Public Class Picturebx

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


'Dim Str As String = "C:\Users\AMIT YADAV\Desktop\"
72
PictureBox1.Image = Image.FromFile("C:\Users\AMIT YADAV\Desktop\Imagename.png")
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
PictureBox1.Height = 250
PictureBox1.Width = 400
Label1.Visible = False
End Sub
Private Sub Picturebx_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Disha College" 'Set the title name for the form
Button1.Text = "Show"
Label1.Text = "Click to display the image"
Label1.ForeColor = ForeColor.Green
End Sub
End Class

ScrollBars Control

A ScrollBar control is used to create and display vertical and horizontal scroll bars on the Windows form.
Property Description

BackColor The BackColor property is used to set the back color of the scroll bar.

Maximum It is used to set or get the maximum value of the Scroll Bar control. By default, it
is 100.

Minimum It is used to get or set the minimum value of the Scroll bar control. By default, it is
0.

SmallChange It is used to obtain or set a value that will be added or subtracted from the property
of the scroll bar control when the scroll bar is moved a short distance.

AutoSize As the name suggests, the AutoSize property is used to get or set a value
representing whether the scroll bar can be resized automatically or not with its
contents.

LargeChange It is used to obtain or set a value that will be added or subtracted from the property
of the scroll bar control when the scroll bar is moved a large distance.

Value It is used to obtain or set a value in a scroll bar control that indicates a scroll box's
current position.

DefaultImeMod It is used to get the default input method Editor (IME) that are supported by
e ScrollBar controls in the Windows Form.

Methods of the ScrollBar Control

Method Description

UpdateScrollInfo It is used to update the ScrollBar control using the Minimum,


maximum, and the value of LargeChange properties.

OnScroll(ScrollEventArgs) It is used to raise the Scroll event in the ScrollBar Control.

OnEnabledChanged It is used to raise the EnabledChanged event in the ScrollBar control.

Select It is used to activate or start the ScrollBar control.


73
OnValueChanged(EventArgs) It is used to raise the ValueChanged event in the ScrollBar control.
Events of the ScrollBar Control
Event Description

AutoSizeChanged The AutoSizeChanged event is found in the ScrollBar control when the value of
the AutoSize property changes.

Scroll The Scroll event is found when the Scroll control is moved.

TextChangedEven It occurs in the ScrollBar control when the value of the text property changes.
t

ValueChanged A ValueChanged event occurs when the property of the value is changed
programmatically or by a scroll event in the Scrollbar Control.

ScrollBar.vb

Public Class ScrollBar


Private Sub ScrollBar_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Disha College" 'Set the title for a Windows Form
Label1.Text = "Use of ScrollBar in Windows Form"
Label1.ForeColor = Color.Blue
Me.AutoScroll = True
Me.VScrollBar1.Minimum = 0
Me.VScrollBar1.Maximum = 100
Me.VScrollBar1.Value = 0
Me.VScrollBar1.BackColor = Color.Blue
Me.HScrollBar1.Minimum = 0
Me.HScrollBar1.Maximum = 100
Me.HScrollBar1.Value = 35
End Sub
End Class

DateTimePicker Control

The DateTimePicker control allows the user to select or display date and time values with a specified format in Windows
Forms. Furthermore, we can determine the current date and time using the Value property of the DateTimePicker control.
Property Description

BackgroundImage It is used to set the background image for the DateTimePicker control.

CalendarFont It is used to set the font style for the calendar in the DateTimePicker control.

CustomFormat The CustomFormat property is used to set the custom date and time format
string in the DateTimePicker control.

Controls It is used to obtain the collection of controls that are stored within the
DateTimePicker control.

Checked A checked property is used to check whether the value property is checked with
a valid date and time in the DateTimePicker control.

Format The Format property of the DateTimePicker is used to set the format for the
Date and time displayed in the Windows Form.
74
MaxDate The MaxDate property of the DateTimePicker is used to set the max data and
time in control selected by the user.

Name The Name property of the DateTimePicker control allows the user to set the
name of the control.

MinimumDateTim It is used to set the minimum date value that can be allowed by control.
e

Methods of the DateTimePicker Control

There are some Methods of the VB.NET DateTimePicker control.


Method Description

Contains(Control) It is used to validate whether the specified control is a child of the


DateTimePicker control or not.

CreateControl() It is used to force the creation of visible control to handle the creation and any
visible child controls.

GetAutoSizeMode( The GetAutoSizeMode() method is used to check the behavior of the


) DateTimePicker control when the AutoAize property is enabled.

ResetBackColor() It is used to reset the back color of the DateTimePicker control.

Select() The Select() method is used to start or activate the DateTimePicker control.

Show() The Show() method is used to display the control to the user.

ToString() The ToString() method is used to return a string that represents the current
DateTimePicker control.

DateTime.vb

Public Class DateTime


Private Sub DateTime_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Disha College"
Button1.Text = "Calculate Days"
Label1.Text = "Calculate the total days from your date of birth to the current date."
Label2.Text = "Total Days"
Label3.Text = "Select the DOB"
Label4.Text = "Current Date"
DateTimePicker1.Format = DateTimePickerFormat.Long
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dp As Date = DateTimePicker1.Value
Dim dp2 As Date = DateTimePicker2.Value
Dim result As TimeSpan = dp.Subtract(dp2)
Dim ds As Integer = result.TotalDays
TextBox1.Text = ds
TextBox1.ForeColor = ForeColor.Red
MsgBox(" Days = " & ds)
End Sub
End Class

75
ProgressBar Control

The Window ProgressBar control is used by the user to acknowledge the progress status of some defined tasks, such as
downloading a large file from the web, copying files, installing software, calculating complex results, and more.
Property Description

BackgroundImage The BackgroundImage property is used to set the background image in the
progressbar control.

MarqueeAnimationSpee It is used to determine the progress status for a progress bar in


d milliseconds.

Padding The padding property is used to create a space between the edges of the
progress bar by setting the value in the progressbar control.

Step It is used to get or set a value in control that calls the PerformStep method
to increase the current state of the progress bar by adding a defined step.

Maximum It is used to set the maximum length of the progress bar control in the
windows form.

Minimum It is used to set or get the minimum value of the progress bar control in
the windows form.

AllowDrop It obtains a value representing whether the progress bar control enables
the user to be dragged onto the form.

Style It is used to set a value that represents how types the progress bar should
be displayed on the Windows Form.

Methods of the ProgressBar Control

Event Description

ForeColor The ForeColor method is used to reset the forecolor to its default value.

ToString The ToString method is used to display the progress bar control by returning the string.

Increment It is used to increase the current state of the progress bar control by defining the
specified time.

PerformSte The PerformStep method is used to increase the progress bar by setting the step
p specified in the ProgressBar property.

Events of the ProgressBar Control

Events Description

Leave The Leave event occurs when the focus leaves the progress bar control.

MouseClick A MouseClick event occurred when the user clicked on the progress bar
control by the mouse.

BackgroundImageChange When the background property changes to the progress bar control, the
d BackgroundImageChanged event changes.
76
TextChanged It occurs when the property of the text is changed in the progress bar
control.

PaddingChanged It occurs when the padding property is changed in the progress bar
control.

Progressbr.vb

Public Class Progressbr


Private Sub Progressbr_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Disha College" 'Set the title name for the form
Button1.Text = "Show"
Label1.Text = "Click to display the progress status of the ProgressBar"
Label1.ForeColor = ForeColor.Green
ProgressBar1.Visible = False

'create a progress bars


Dim Progressbr2 As ProgressBar = New ProgressBar()

'set the progressbar position


Progressbr2.Location = New Point(60, 70)
'set the values for Progressbr2
Progressbr2.Minimum = 0
Progressbr2.Maximum = 500
Progressbr2.Value = 470

'add the progress bar status to the form.


Me.Controls.Add(Progressbr2)

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


ProgressBar1.Visible = True

Dim i As Integer
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 300

For i = 0 To 300 Step 1


ProgressBar1.Value = i
If i > ProgressBar1.Maximum Then
i = ProgressBar1.Maximum
End If
Next
MsgBox("Successfully Completed")
End Sub
End Class

77
UNIT 4

78
Unit IV
Classes and Object

A class is a group of different data members or objects with the same properties, processes, events of
an object, and general relationships to other member functions.
we can say that it is like a template or architect that tells what data and function will appear when it
is included in a class object. For example, it represents the method and variable that will work on the
object of the class.
Objects are the basic run-time units of a class. Once a class is defined, we can create any number of
objects related to the class to access the defined properties and methods. For example, the Car is the
Class name, and the speed, mileage, and wheels are attributes of the Class that can be accessed by the
Object.
Creating the
Class
[ Access_Specifier ] [ MustInherit | NotInheritable ] Class ClassName
' Data Members or Variable Declaration
' Methods Name
' Statement to be executed
End Class

Where,
Access_Specifier: It defines the access levels of the class, such as Public, Private or Friend, Protected,
Protected Friend, etc. to use the method. (It is an optional parameter).
MustInherit: It is an optional parameter that specifies that the class can only be used as a base class,
and the object will not directly access the base class or the abstract class.
NotInheritable: It is also an optional parameter that representing the class not being used as a base
class.
Implements: It is used to specify interfaces from which the class inherits (optional).
My_program.vb
Public Class My_program
' properties, method name, etc
' Statement to be executed
End Class

In the above syntax, we have created a class with the name 'My_program' using the Class keyword.
The Syntax for creating an object
Dim Obj_Name As Class_Name = New Class_Name() ' Declaration of object
Obj_Name.Method_Name() ' Access a method using the object
In the above syntax, we have created an instance (Obj_Name) for the class Class_Name. By using the
object name 'Obj_Name' to access all the data members and the method name of Class_Name.
Let's create a program to find the Area and Parameter of a rectangle using the class and object in
VB.NET.

My_program.vb
Imports System
Module My_program
Sub Main()
Dim rect As Rectangle = New Rectangle() 'create an object
Dim rect2 As Rectangle = New Rectangle() 'create an object
79
Dim area, para As Integer

'rect specification
rect.setLength = (5)
rect.setBreadth= (6)

'rect2 specification
rect2.setLength = (5)
rect2.setBreadth = (10)
'Area of rectangle
area = rect.length * rect.Breadth
'area = rect.GetArea()
Console.WriteLine(" Area of Rectangle is {0}", area)

'Parameter of rectangle
'para = rect.GetParameter()
para = 2 (rect2.length + rect.Breadth)
Console.WriteLine(" Parameter of Rectangle is {0}", para)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
Public Class Rectangle
Public length As Integer
Public Breadth As Integer
Public Sub setLength(ByVal len As Integer)
length = len
End Sub

Public Sub setBreadth(ByVal bre As Integer)


Breadth = bre
End Sub
Public Function GetArea() As Integer
Return length * Breadth
End Function

Public Function GetParameter() As Integer


Return 2 * (length + Breadth)
End Function
End Class
End Module

Method Overloading

In visual basic, Method Overloading means defining multiple methods with the same name but with
different parameters.
By using Method Overloading, we can perform different tasks with the same method name by passing
different parameters.
Suppose, if we want to overload a method in visual basic, we need to define another method with the same
name but with different signatures.
In visual basic, the Method Overloading is also called as compile time polymorphism or early binding.
Visual Basic Method Overloading Example
80
Following is the example of implementing a method overloading in a visual basic programming language.

Module Module1
Public Class Calculate
Public Sub AddNumbers(ByVal a As Integer, ByVal b As Integer)
Console.WriteLine("a + b = {0}", a + b)
End Sub
Public Sub AddNumbers(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer)
Console.WriteLine("a + b + c = {0}", a + b + c)
End Sub
End Class
Sub Main(ByVal args As String())
Dim c As Calculate = New Calculate()
c.AddNumbers(1, 2)
c.AddNumbers(1, 2, 3)
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module

Constructor

In visual basic, Constructor is a method and it will invoke automatically whenever an instance
of class or struct is created. The constructor is useful to initialize and set default values for the data members of
the new object.

In case, if we create a class without having any constructor, the compiler will automatically create a one default
constructor for that class. So, there is always one constructor that will exist in every class.

In visual basic, a class can contain more than one constructor with a different type of arguments and the
constructors will never return anything, so we don’t need to use any return type, not even void while defining the
constructor method in the class.

Constructor Syntax
As discussed, the constructor is a method and it won’t contain any return type. If we want to create a constructor in
visual basic, we need to create a method with New keyword.

Following is the syntax of creating a constructor in visual basic programming language.


In visual basic, Constructor is a method and it will invoke automatically whenever an instance
of class or struct is created. The constructor is useful to initialize and set default values for the data members of
the new object.

In case, if we create a class without having any constructor, the compiler will automatically create a one default
constructor for that class. So, there is always one constructor that will exist in every class.

In visual basic, a class can contain more than one constructor with a different type of arguments and the
constructors will never return anything, so we don’t need to use any return type, not even void while defining the
constructor method in the class.

Following is the syntax of creating a constructor in visual basic programming language.


Public Class User
' Constructor
Public Sub New()
' Your Custom Code
End Sub
81
End Class
If you observe the above syntax, we created a class called “User” and a method with New keyword. Here the
method New() will become a constructor of our class.

Constructor Types
In visual basic, we have a different type of constructors available, those are
Default Constructor
Parameterized Constructor
Copy Constructor
Private Constructor
Now, we will learn about each constructor in detail with examples in a visual basic programming language.

Default Constructor

In visual basic, if we create a constructor without having any parameters, we will call it as default
constructor and the instance of the class will be initialized without any parameter values.

Following is the example of defining the default constructor in visual basic programming language.
Module Module1
Class User
Public name, location As String
' Default Constructor
Public Sub New()
name = "Suresh Dasari"
location = "Hyderabad"
End Sub
End Class
Sub Main()
' The constructor will be called automatically once the instance of the class created
Dim user As User = New User()
Console.WriteLine(user.name)
Console.WriteLine(user.location)
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module

Parameterized Constructor

In visual basic, if we create a constructor with at least one parameter, we will call it a parameterized constructor and
every time the instance of the class must be initialized with parameter values.

Following is the example of defining the parameterized constructor in a visual basic programming language.
Module Module1
Class User
Public name, location As String
' Parameterized Constructor
Public Sub New(ByVal a As String, ByVal b As String)
name = a
location = b
End Sub
End Class
82
Sub Main()
' The constructor will be called automatically once the instance of the class created
Dim user As User = New User("Suresh Dasari", "Hyderabad")
Console.WriteLine(user.name)
Console.WriteLine(user.location)
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module

Constructor Overloading

In visual basic, we can overload the constructor by creating another constructor with the same method name but
with different parameters.

Following is the example of implementing a constructor overloading in a visual basic programming language.
Module Module1
Class User
Public name, location As String
' Default Constructor
Public Sub New()
name = "Suresh Dasari"
location = "Hyderabad"
End Sub
' Parameterized Constructor
Public Sub New(ByVal a As String, ByVal b As String)
name = a
location = b
End Sub
End Class
Sub Main()
' Default Constructor will be called
Dim user As User = New User()
' Parameterized Constructor will be called
Dim user1 As User = New User("Rohini Alavala", "Guntur")
Console.WriteLine(user.name & ", " & user.location)
Console.WriteLine(user1.name & ", " & user1.location)
Console.WriteLine(vbLf & "Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module

Destructor

In visual basic, Destructor is a special method of a class and it is useful in class to destroy the object or instances
of classes. The destructor in visual basic will invoke automatically whenever the class instances become
unreachable.

The following are the properties of destructor in a visual basic programming language.
In visual basic, destructors can be used only in classes and a class can contain only one destructor.
The destructor in class can be represented by using Finalize() method.
The destructor in visual basic won’t accept any parameters and access modifiers.
The destructor will invoke automatically, whenever an instance of a class is no longer needed.
The destructor automatically invoked by garbage collector whenever the class objects that are no longer needed in
83
an application.
Destructor Syntax

Following is the syntax of defining the destructor in visual basic programming language.
Class User
' Destructor
Protected Overrides Sub Finalize()
' Your Code
End Sub
End Class
If you observe the above syntax, we created a destructor using Finalize() method.
Destructor Example
Following is the example of using destructor in a visual basic programming language to destruct the unused objects
of the class.
Module Module1
Class User
Public Sub New()
Console.WriteLine("An Instance of class created")
End Sub
Protected Overrides Sub Finalize()
Console.WriteLine("An Instance of class destroyed")
End Sub
End Class
Sub Main()
Details()
GC.Collect()
Console.ReadLine()
End Sub
Public Sub Details()
Dim user As User = New User()
End Sub
End Module

If you observe the above example, we created a class with default constructor and destructor. Here, we created
an instance of class “User” in Details() method and whenever the Details function execution is done, then the
garbage collector (GC) automatically will invoke the destructor in User class to clear the object of class.

Inheritance
In visual basic, Inheritance is one of the primary concepts of object-oriented programming (OOP) and it is useful
to inherit the properties from one class (base) to another (child) class.

The inheritance will enable us to create a new class by inheriting the properties from other classes to reuse, extend
and modify the behavior of other class members based on our requirements.

In visual basic inheritance, the class whose members are inherited is called a base (parent) class and the class that
inherits the members of base (parent) class is called a derived (child) class.
Inheritance Syntax
Following is the syntax of implementing an inheritance to define derived class that inherits the properties of base
class in a visual basic programming language.
<access_modifier> Class <base_class_name>
// Base class Implementation
End Class

<access_modifier> Class <derived_class_name>


84
Inherits base_class_name
// Derived class implementation
End Class
If you observe the above syntax, we are inheriting the properties of base class into child class to improve the code
reusability.

Following is the simple example of implementing inheritance in a visual basic programming language.
Public Class X
Public Sub GetDetails()
' Method implementation
End Sub
End Class

Public Class Y
Inherits X
' your class implementation
End Class

Class Program
Public Shared Sub Main(ByVal args As String())
Dim y As Y = New Y()
y.GetDetails()
End Sub
End Class

If you observe the above example, we defined a class “X” with a method called “GetDetails” and the class “Y” is
inheriting from the class “X”. After that, we are calling a “GetDetails” method by using an instance of derived
class “Y”.

In visual basic, it’s not possible to inherit the base class constructors in the derived class and the accessibility of
other members of the base class also depends on the access modifiers which we used to define those members in
the base class.
Inheritance Example
Following is the example of implementing an inheritance by defining two classes in a visual basic programming
language.
Public Class User
Public Name As String
Private Location As String
Public Sub New()
Console.WriteLine("Base Class Constructor")
End Sub
Public Sub GetUserInfo(ByVal loc As String)
Location = loc
Console.WriteLine("Name: {0}", Name)
Console.WriteLine("Location: {0}", Location)
End Sub
End Class

Public Class Details


Inherits User
Public Age As Integer
Public Sub New()
Console.WriteLine("Child Class Constructor")
End Sub
85
Public Sub GetAge()
Console.WriteLine("Age: {0}", Age)
End Sub
End Class

Class Program
Public Shared Sub Main(ByVal args As String())
Dim d As Details = New Details()
d.Name = "Suresh Dasari"
' Compile Time Error
' d.Location = "Hyderabad";
d.Age = 32
d.GetUserInfo("Hyderabad")
d.GetAge()
Console.WriteLine(vbLf & "Press Any Key to Exit..")
Console.ReadLine()
End Sub
End Class
Multi-Level Inheritance
Generally, visual basic supports only single inheritance that means a class can only inherit from one base class.
However, in visual basic the inheritance is transitive and it allows you to define a hierarchical inheritance for a set
of types and it is called a multi-level inheritance.

For example, suppose if class C is derived from class B, and class B is derived from class A, then class C will inherit
the members declared in both class B and class A.

Public Class A
' Implementation
End Class

Public Class B
Inherits A
' Implementation
End Class

Public Class C
Inherits B
' Implementation
End Class

Example:2 …………
Public Class A
Public Name As String
Public Sub GetName()
Console.WriteLine("Name: {0}", Name)
End Sub
End Class

Public Class B
Inherits A
Public Location As String
Public Sub GetLocation()
Console.WriteLine("Location: {0}", Location)
86
End Sub
End Class

Public Class C
Inherits B
Public Age As Integer
Public Sub GetAge()
Console.WriteLine("Age: {0}", Age)
End Sub
End Class

ClassProgram
Public Shared Sub Main(ByVal args As String())
Dim c As C = New C()
c.Name = "Suresh Dasari"
c.Location = "Hyderabad"
c.Age = 32
c.GetName()
c.GetLocation()
c.GetAge()
Console.WriteLine(vbLf & "Press Any Key to Exit..")
Console.ReadLine()
End Sub
End Class

Method Overriding

In visual basic, Method Overriding means override a base class method in the derived class by creating
a method with the same name and signatures to perform a different task. The Method Overriding in visual basic can
be achieved by using Overridable & Overrides keywords along with the inheritance principle.

Suppose, if we want to change the behavior of the base class method in a derived class, we need to use method
overriding. The base class method which we want to override in the derived class that needs to be defined with
an Overridable keyword and we need to use Overrides keyword in derived class while defining the method with
the same name and parameters then only we can override the base class method in the derived class.

In visual basic, the Method Overriding is also called as run time polymorphism or late binding. Following is
the code snippet of implementing a method overriding in a visual basic programming language.
' Base Class
Public Class Users
Public Overridable Sub GetInfo()
Console.WriteLine("Base Class")
End Sub
End Class

'Derived Class
Public Class Details
Inherits Users
Public Overrides Sub GetInfo()
Console.WriteLine("Derived Class")
End Sub
End Class

If you observe the above code snippet, we created two classes (“Users”, “Details”) and the derived class (Details)
87
is inheriting the properties from the base class (Users) and we are overriding the base class method GetInfo in
the derived class by creating a method with same name and parameters, this is called a method overriding in
visual basic.

Here, we defined the GetInfo method with an Overridable keyword in the base class to allow derived class to
override that method using the Overrides keyword.

As discussed, only the methods with Overridable keyword in the base class are allowed to override in the derived
class using Overrides keyword.

Method Overriding Example


Following is the example of implementing a method overriding in a visual basic programming language.

Module Module1
Public Class BClass
Public Overridable Sub GetInfo()
Console.WriteLine("Learn C# Tutorial")
End Sub
End Class
Public Class DClass
Inherits BClass
Public Overrides Sub GetInfo()
Console.WriteLine("Welcome ")
End Sub
End Class
Sub Main(ByVal args As String())
Dim d As DClass = New DClass()
d.GetInfo()
Dim b As BClass = New BClass()
b.GetInfo()
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module

88
UNIT 5

89
Unit V

ADO.NET

ADO.NET provides a bridge between the front end controls and the back end database. The ADO.NET objects
encapsulate all the data access operations and the controls interact with these objects to display data, thus hiding the details
of movement of data.
The following figure shows the ADO.NET objects at a glance:

The DataSet Class

The dataset represents a subset of the database. It does not have a continuous connection to the database.
To update the database a reconnection is required. The DataSet contains DataTable objects and DataRelation objects.
The DataRelation objects represent the relationship between two tables.

Data Providers

Data provider is used to connect to the database, execute commands and retrieve the record.
It is lightweight component with better performance. It also allows us to place the data into DataSet to use it further in our
application.
The .NET Framework provides the following data providers that we can use in our application.

.NET Framework data provider Description

.NET Framework Data Provider for It provides data access for Microsoft SQL Server. It requires
SQL Server the System.Data.SqlClient namespace.

.NET Framework Data Provider for It is used to connect with OLE DB. It requires
OLE DB the System.Data.OleDb namespace.

.NET Framework Data Provider for It is used to connect to data sources by using ODBC. It requires
ODBC the System.Data.Odbc namespace.

.NET Framework Data Provider for It is used for Oracle data sources. It uses
Oracle the System.Data.OracleClient namespace.

90
.NET Framework Data Provider for It provides data access for Microsoft SQL Server Compact 4.0. It requires
SQL Server Compact 4.0. the System.Data.SqlServerCe namespace.

Data Providers Objects


Following are the core object of Data Providers.

Object Description

Connection It is used to establish a connection to a specific data source.

Command It is used to execute queries to perform database operations.

DataReader It is used to read data from data source. The DbDataReader is a base class for all DataReader objects.

DataAdapter The base class for all DataAdapter objects is the DbDataAdapter It populates a DataSet and resolves
updates with the data source class.

Data Provider for SQL Server


Data provider for SQL Server is a lightweight component. It provides better performance because it directly access SQL
Server without any middle connectivity layer. In early versions, it interacts with ODBC layer before connecting to the
SQL Server that created performance issues.
The .NET Framework Data Provider for SQL Server classes is located in the System.Data.SqlClient namespace. We can
include this namespace in our C# application by using the following syntax.
using System.Data.SqlClient;

This namespace contains the following important classes.

Class Description

SqlConnection It is used to create SQL Server connection. This class cannot be inherited.

SqlCommand It is used to execute database queries. This class cannot be inherited.

SqlDataAdapter It represents a set of data commands and a database connection that are used to fill the DataSet. This
class cannot be inherited.

SqlDataReader It is used to read rows from a SQL Server database. This class cannot be inherited.

SqlException This class is used to throw SQL exceptions. It throws an exception when an error is occurred. This
class cannot be inherited.

The DataAdapter Object


The DataAdapter object acts as a mediator between the DataSet object and the database. This helps the Dataset to contain
data from multiple databases or other data source.
The DataReader Object
The DataReader object is an alternative to the DataSet and DataAdapter combination. This object provides a connection
oriented access to the data records in the database. These objects are suitable for read-only access, such as populating a list
and then breaking the connection.

Steps How to Connect Access Database in VB.Net


Step 1: Create an MS Access Database.
91
Open an MS Access Database in your Computer and Create a Blank Database and Save it as “inventorydb.accdb”.
Step 2: Create a Database Table.
To create a table, follow the image below and save it as “tblitems”.

Step 3: Populate the table.


Add sample records in the table. follow the sample records in the image below.

Step 4: Create a VB.Net Application.


Open Visual Studio and Create a Visual Basic Application project and Save it as “connectvbaccess”.
Step 5: Design the user interface.
To design the form, you need to follow the image below.

92
Step 6: Add New Data Source.
On the menu, click data and select “Add new Data Source..”

Step 7: Choose a Data Source Type


Select Database and click Next.

93
Step 7: Choose a Data Source

Click new Connection then, Select Microsoft AccessDatabase file and, Click Continue. Follow the image below.

94
Step 9: Add Connection
First, click Browse Button then, Select “inventorydb.accdb”, Lastly, Click Open.

Step 10: Test Connection


To test the connection, click the “Test Connection” button, finally click “OK” button at the side of the “Cancel” button.

95
Step 11: Copy the Connection String.
Copy the connection string so that we can use this in our next step.

Step 12: Start Coding.


96
In this final step, we will now start adding functionality to our vb.net program by adding some functional codes.
Code To Connect Access Database in VB.Net
Double the “Form1” and add the following code under “Public Class Form1”.

Dim con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\joken\


1
Documents\inventorydb.accdb")
2
The Code above started with a Declaration of Variable name “con” with an Ole Object Type OledbConnection.
Inside OledbConnection, we pasted the connection string we copied from the “Step 11” instructions.
Test the Connection of Access database in VB.Net
To test the Connection between ms access database and VB.Net, Double click the form1 add the following code under
“Form1_Load” events.

1 Try
2 con.Open()
3
4 If con.State = ConnectionState.Open Then
5 MsgBox("Connected")
6 Else
7 MsgBox("Not Connected!")
8
9 End If
10 Catch ex As Exception
11 MsgBox(ex.Message)
12 Finally
13 con.Close()
14
15 End Try
We use try-catch to the exceptions that may occur during runtime.
open the connection
check using if statement if the connection is open
‘Display a message box if successfully connected or Not
close the connection

Imports System.Data.OleDb
Public Class Form1
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Administrator\
Documents\demo.accdb")
Dim cmd As New OleDbCommand
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DemoDataSet.Table1' table. You can move, or remove it, as needed.
con.Open()
Me.Table1TableAdapter.Fill(Me.DemoDataSet.Table1)
cmd.Connection = con
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


Table1BindingSource.AddNew()
97
cmd.CommandText = "insert into table1 values( '" & TextBox1.Text & "','" & TextBox2.Text & "')"
cmd.ExecuteNonQuery()

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


Table1BindingSource.EndEdit()
Table1TableAdapter.Update(DemoDataSet.Table1)
MsgBox("hi")
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click


Table1BindingSource.RemoveCurrent()
If Me.DataGridView1.Rows.Count > 0 Then
cmd.CommandText = "delete from table1 where name='" & TextBox1.Text & "'"
cmd.ExecuteNonQuery()
' Me.Table1TableAdapter.Fill(Me.DemoDataSet.Table1)
End If

End Sub

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click


Table1BindingSource.MoveNext()
End Sub

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click


Table1BindingSource.MovePrevious()
End Sub
End Class
…………………………………………………………………………………………………………………………………
…………..
Imports System.Data.OleDb
Public Class Form1
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Administrator\
Documents\demo.accdb")
Dim cmd As New OleDbCommand
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DemoDataSet.Table1' table. You can move, or remove it, as needed.
con.Open()
Me.Table1TableAdapter.Fill(Me.DemoDataSet.Table1)
cmd.Connection = con
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


Table1BindingSource.AddNew()
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


Table1BindingSource.EndEdit()
Table1TableAdapter.Update(DemoDataSet.Table1)
cmd.CommandText = "insert into table1 values( '" & TextBox1.Text & "','" & TextBox2.Text & "')"
cmd.ExecuteNonQuery()
MsgBox("hi")
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click


98
Table1BindingSource.RemoveCurrent()
If Me.DataGridView1.Rows.Count > 0 Then
cmd.CommandText = "delete from table1 where name='" & TextBox1.Text & "'"
cmd.ExecuteNonQuery()
' Me.Table1TableAdapter.Fill(Me.DemoDataSet.Table1)
End If

End Sub

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click


Table1BindingSource.MoveNext()
End Sub

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click


Table1BindingSource.MovePrevious()
End Sub
End Class

99

You might also like