Sie sind auf Seite 1von 37

VB.

NET Tutorial and source code


VB.NET is an update to Visual Basic that targets
Microsofts .NET Framework. VB.NET has a lot of
similarities to Visual Basic but also some
differences. VB.NET is an object-oriented
language, which supports the abstraction,
encapsulation, inheritance, and polymorphism features. It is the
most productive tool for rapidly creating a wide range of Windows,
Web, Mobile, and Office applications
built on the .NET Framework.

The Visual Basic language is designed to


be human readable and accessible to
everyone from novice programmers to
advanced system architects. All of this
is built on top of the .NET Framework,
which guarantees that programs written
in Visual Basic run with unsurpassed
scalability and reliability. The .NET
Framework provides VB.Net
programmers with the ability to create
fully object oriented programs (OOPs),
just like the ones created using Java,
C# or C++. Also programs written in
VB.Net will interoperate seamlessly with
programs written in any other .NET
languages such as Visual C#, Visual J#, or Visual
C++.

Many programmers says VB.Nets ease of use as


the key to its success. Using VB.NET, you can create a wide variety
of applications, such as a Console Applications, that displays its
output in an MS-DOS-like window, Windows Applications that often
displays a form-based interface, Web Applications, Web Services,
Mobile Applications etc. I hope this site will help you to acquire the
skills and knowledge necessary to develop various types of
applications in VB.NET in a simplified manner rather than in a
complex way.
What is Microsoft .Net Framework
The Microsoft .Net Framework is a platform that provides tools and
technologies you need to build Networked Applications as well as
Distributed Web Services and Web Applications. The .Net
Framework provides the necessary compile time and run-time
foundation to build and run any language that conforms to the
Common Language Specification (CLS).The main two components of
.Net Framework are Common Language Runtime (CLR) and .Net
Framework Class Library (FCL).

The Common Language Runtime (CLR) is the runtime environment


of the .Net Framework , that executes and manages all running
code like a Virtual Machine. The .Net Framework Class Library (FCL)
is a huge collection of language-independent and type-safe reusable
classes. The .Net Framework Class Libraries (FCL) are arranged into
a logical grouping according to their functionality and usability is
called Namespaces. The following lessosns describes how to .Net
Framework manages the code in compile time and run time .

Microsoft .NET Framework Versions, Year and Download Links

.NET Framework 1.0 (2002-02-13) Download


.NET Framework 1.1 (2003-04-24) Download

.NET Framework 2.0 (2005-11-07) Download

.NET Framework 3.0 (2006-11-06) Download

.NET Framework 3.5 (2007-11-19) Download

.NET Framework 4.0 (2010-04-12) Download

.NET Framework 4.5 (2012-08-15) Download

How to Microsoft .Net Framework


Microsoft .Net Languages Source Code are compiled into Microsoft
Intermediate Language (MSIL) . MSIL we can call it as Intermediate
Language (IL) or Common Intermediate Language (CIL). Microsoft
Intermediate Language (MSIL) is a CPU independent set of
instructions that can be converted to the native code. Metadata also
created in the course of compile time with Microsoft Intermediate
Language (MSIL) and stored it with the compiled code . Metadata is
completely self-describing . Metadata is stored in a file called
Manifest, and it contains information about the members, types,
references and all the other data that the Common Language
Runtime (CLR) needs for execution .

The Common Language Runtime (CLR) uses metadata to locate and


load classes, generate native code, provide security, and execute
Managed Code. Both Microsoft Intermediate Language (MSIL) and
Metadata assembled together is known as Portable Executable (PE)
file. Portable Executable (PE) is supposed to be portable across all
32-bit operating systems by Microsoft .Net Framework.

During the runtime the Common Language Runtime (CLR)'s Just In


Time (JIT) compiler converts the Microsoft Intermediate Language
(MSIL) code into native code to the Operating System. The native
code is Operating System independent and this code is known as
Managed Code , that is, the language's functionality is managed by
the .NET Framework . The Common Language Runtime (CLR)
provides various Just In Time (JIT) compilers, and each works on a
different architecture depends on Operating Systems, that means
the same Microsoft Intermediate Language (MSIL) can be executed
on different Operating Systems. From the following section you can
see how Common Language Runtime (CLR) functions .

Can I run .Net Framework on Linux ?

Microsoft .Net framework is proprietary Windows software and


requires the Windows API to run. It will not run natively in Linux.
But there is an open source implementation of .NET Framework
called MONO which has almost the same functionality of the MS
.NET.

Mono Project

Mono is a free and open source project led by Xamarin. It is an


open source implementation of Microsoft's .NET Framework based
on the ECMA standards for C# and the Common Language Runtime.
More about : MONO

How to Common Language Runtime


The Common Language Runtime (CLR) is an Execution Environment
. It works as a layer between Operating Systems and the
applications written in .Net languages that conforms to the Common
Language Specification (CLS). The main function of Common
Language Runtime (CLR) is to convert the Managed Code into native
code and then execute the Program. The Managed Code compiled
only when it needed, that is it converts the appropriate instructions
when each function is called . The Common Language Runtime
(CLR) 's Just In Time (JIT) compilation converts Intermediate
Language (MSIL) to native code on demand at application run time.

During the execution of the program ,the Common Language


Runtime (CLR) manages memory, Thread execution, Garbage
Collection (GC) , Exception Handling, Common Type System (CTS),
code safety verifications, and other system services. The CLR (
Common Language Runtime ) defines the Common Type System
(CTS), which is a standard type system used by all .Net languages .
That means all .NET programming languages uses the same
representation for common Data Types , so Common Language
Runtime (CLR) is a language-independent runtime environment .
The Common Language Runtime (CLR) environment is also referred
to as a managed environment, because during the execution of a
program it also controls the interaction with the Operating System.
In the coming section you can see what are the main functions of
Common Language Runtime (CLR).

How to Common Language Runtime - CLR


The Common Language Runtime (CLR) is a an Execution
Environment . Common Language Runtime (CLR)'s main tasks are
to convert the .NET Managed Code to native code , manage running
code like a Virtual Machine and also controls the interaction with the
Operating System.

Common Language Runtime (CLR) manages Thread executions,


Memory Management that is allocation of Objects and Buffers ,
Garbage Collection (GC) - Clean up the unused Objects and buffers ,
Exception Handling, Common Type System (CTS) that is all .NET
language that conforms to the Common Language Specification
(CLS) have the same primitive Data Types, Code safety verifications
- code can be verified to ensure type safety, Language integration
that is Common Language Runtime (CLR) follow a set of
specification called Common Language Specification (CLS) , this will
ensure the interoperability between languages, Integrated security
and other system services.
.Net Framework Class Library (FCL)
The .Net Framework class library (FCL) provides the core
functionality of .Net Framework architecture . The .Net Framework
Class Library (FCL) includes a huge collection of reusable classes ,
interfaces, and value types that expedite and optimize the
development process and provide access to system functionality.

The .Net Framework class library (FCL) organized in a hierarchical


tree structure and it is divided into Namespaces. Namespaces is a
logical grouping of types for the purpose of identification.
Framework class library (FCL) provides the consistent base types
that are used across all .NET enabled languages. The Classes are
accessed by namespaces, which reside within Assemblies. The
System Namespace is the root for types in the .NET Framework.
The .Net Framework class library (FCL) classes are managed classes
that provide access to System Services . The .Net Framework class
library (FCL) classes are object oriented and easy to use in program
developments. Moreover, third-party components can integrate with
the classes in the .NET Framework.

Common Language Specification - CLS


Common Language Specification (CLS) is a set of basic language
features that .Net Languages needed to develop Applications and
Services , which are compatible with the .Net Framework. When
there is a situation to communicate Objects written in different .Net
Complaint languages , those objects must expose the features that
are common to all the languages . Common Language Specification
(CLS) ensures complete interoperability among applications,
regardless of the language used to create the application.

Common Language Specification (CLS) defines a subset of Common


Type System (CTS) . Common Type System (CTS) describes a set
of types that can use different .Net languages have in common ,
which ensure that objects written in different languages can interact
with each other. Most of the members defined by types in the .NET
Framework Class Library (FCL) are Common Language Specification
(CLS) compliant Types. Moreover Common Language Specification
(CLS) standardized by ECMA .

Common Type System - CTS


Common Type System (CTS) describes a set of types that can be
used in different .Net languages in common . That is , the Common
Type System (CTS) ensure that objects written in different .Net
languages can interact with each other. For Communicating
between programs written in any .NET complaint language, the
types have to be compatible on the basic level .

These types can be Value Types or Reference Types . The Value


Types are passed by values and stored in the stack. The Reference
Types are passed by references and stored in the heap. Common
Type System (CTS) provides base set of Data Types which is
responsible for cross language integration. The Common Language
Runtime (CLR) can load and execute the source code written in any
.Net language, only if the type is described in the Common Type
System (CTS) .Most of the members defined by types in the
.NET Framework Class Library (FCL) are Common Language
Specification(CLS) compliant Types.

Microsoft Intermediate Language - MSIL


MSIL stands for Microsoft Intermediate Language. We can call it as
Intermediate Language (IL) or Common Intermediate Language
(CIL). During the compile time , the compiler convert the source
code into Microsoft Intermediate Language (MSIL) .Microsoft
Intermediate Language (MSIL) is a CPU-independent set of
instructions that can be efficiently converted to the native code.
During the runtime the Common Language Runtime (CLR)'s Just In
Time (JIT) compiler converts the Microsoft Intermediate Language
(MSIL) code into native code to the Operating System.
When a compiler produces Microsoft Intermediate Language (MSIL),
it also produces Metadata. The Microsoft Intermediate Language
(MSIL) and Metadata are contained in a portable executable (PE) file
. Microsoft Intermediate Language (MSIL) includes instructions for
loading, storing, initializing, and calling methods on objects, as well
as instructions for arithmetic and logical operations, control flow,
direct memory access, exception handling, and other operations

Portable Executable (PE) File Format


The Portable Executable (PE) format is a file format for executables,
object code, and DLLs, used in 32-bit and 64-bit versions of
Windows operating systems.

The PE file format was defined to provide the best way for the
Windows Operating System to execute code and also to store the
essential data which is needed to run a program. Portable
Executable File Format is derived from the Microsoft Common
Object File Format (COFF).

Just In Time Compiler - JIT


The .Net languages , which is conforms to the Common Language
Specification (CLS), uses its corresponding runtime to run the
application on different Operating Systems . During the code
execution time, the Managed Code compiled only when it is needed,
that is it converts the appropriate instructions to the native code for
execution just before when each function is called. This process is
called Just In Time (JIT) compilation, also known as Dynamic
Translation . With the help of Just In Time Compiler (JIT)
the Common Language Runtime (CLR) doing these tasks.

The Common Language Runtime (CLR) provides various Just In


Time compilers (JIT) and each works on a different architecture
depending on Operating System. That is why the same Microsoft
Intermediate Language (MSIL) can be executed on different
Operating Systems without rewrite the source code. Just In Time
(JIT) compilation preserves memory and save time during
application initialization. Just In Time (JIT) compilation is used to
run at high speed, after an initial phase of slow interpretation. Just
In Time Compiler (JIT) code generally offers far better performance
than interpreters.

Managed Code
Managed Code in Microsoft .Net Framework, is the code that has
executed by the Common Language Runtime (CLR) environment.
On the other hand Unmanaged Code is directly executed by the
computer's CPU. Data types, error-handling mechanisms, creation
and destruction rules, and design guidelines vary between managed
and unmanaged object models.

The benefits of Managed Code include programmers convenience


and enhanced security . Managed code is designed to be more
reliable and robust than unmanaged code , examples are Garbage
Collection , Type Safety etc. The Managed Code running in a
Common Language Runtime (CLR) cannot be accessed outside the
runtime environment as well as cannot call directly from outside the
runtime environment. This makes the programs more isolated and
at the same time computers are more secure . Unmanaged Code
can bypass the .NET Framework and make direct calls to the
Operating System. Calling unmanaged code presents a major
security risk.

Microsoft .Net Metadata


Metadata in .Net is binary information which describes the
characteristics of a resource . This information include Description of
the Assembly , Data Types and members with their declarations and
implementations, references to other types and members , Security
permissions etc. A module's metadata contains everything that
needed to interact with another module.

During the compile time Metadata created with Microsoft


Intermediate Language (MSIL) and stored in a file called a Manifest
. Both Metadata and Microsoft Intermediate Language (MSIL)
together wrapped in a Portable Executable (PE) file. During the
runtime of a program Just In Time (JIT) compiler of the Common
Language Runtime (CLR) uses the Metadata and converts Microsoft
Intermediate Language (MSIL) into native code. When code is
executed, the runtime loads metadata into memory and references
it to discover information about your code's classes, members,
inheritance, and so on. Moreover Metadata eliminating the need for
Interface Definition Language (IDL) files, header files, or any
external method of component reference.

Microsoft .Net Assembly


Microsoft .Net Assembly is a logical unit of
code, that contains code which theCommon
Language Runtime (CLR) executes. It is the
smallest unit of deployment of a .net application
and it can be a .dll or an exe . Assembly is
really a collection of types and resource
information that are built to work together and
form a logical unit of functionality. It include both executable
application files that you can run directly from Windows without the
need for any other programs (.exe files), and libraries (.dll files) for
use by other applications.

Assemblies are the building blocks of .NET Framework applications.


During the compile time Metadata is created with Microsoft
Intermediate Language (MSIL) and stored in a file called Assembly
Manifest . Both Metadata and Microsoft Intermediate Language
(MSIL) together wrapped in a Portable Executable (PE) file.
Assembly Manifest contains information about itself. This
information is called Assembly Manifest, it contains information
about the members, types, references and all the other data that
the runtime needs for execution.

Every Assembly you create contains one or more


program files and a Manifest. There are two
types program files : Process Assemblies (EXE)
and Library Assemblies (DLL). Each Assembly
can have only one entry point (that is, DllMain,
WinMain, or Main).

We can create two types of Assembly:

1. Private Assembly

2. Shared Assembly

A private Assembly is used only by a single application, and usually


it is stored in that application's install directory. A shared Assembly
is one that can be referenced by more than one application. If
multiple applications need to access an Assembly, we should add
the Assembly to the Global Assembly Cache (GAC). There is also a
third and least known type of an assembly: Satellite Assembly . A
Satellite Assembly contains only static objects like images and other
non-executable files required by the application.

.Net Assembly - Interview Questions


Difference between NameSpace and Assembly

A namespace is a logical grouping of types. An assembly can


contain types in multiple namespaces and a single namespace can
be spread across assemblies. More about... NameSpace and
Assembly

How to add and remove Assembly from GAC ?

Each computer that .Net Framework is installed has a


Global Assembly Cache, which is located in the
Assembly folder in the Windows directory, normally
C:\WinNT\Assembly. The Global Assembly Cache
tool(Gacutil.exe) allows you to view and manipulate
the contents of the global assembly cache. More about.. Add,
Remove Assembly

What is .Net Assembly Qualified Name ?

An Assembly qualified name is the internal name of the assembly,


combined with the Assembly Version, Culture, and public Key: these
combination make it unique. More about... Assembly Qualified
Name

How to Assembly versioning ?

The AssemblyVersion attribute assigns the version number of the


assembly, and this is embedded in the manifest. Version
information for an assembly consists of the following four values : a
major and minor version number, and two further optional build and
revision numbers. More about... Assembly versioning

.Net Assembly Manifest


An Assembly Manifest is a file that containing Metadata about .NET
Assemblies. Assembly Manifest contains a collection of data that
describes how the elements in the assembly relate to each other. It
describes the relationship and dependencies of the components in
the Assembly, versioning information, scope information and the
security permissions required by the Assembly.

The Assembly Manifest can be stored in Portable Executable (PE) file


with Microsoft Intermediate Language (MSIL) code. You can add or
change some information in the Assembly Manifest by using
assembly attributes in your code. The Assembly Manifest can be
stored in either a PE file (an .exe or .dll) with Microsoft Intermediate
Language (MSIL) code or in a standalone PE file that contains only
assembly manifest information. Using ILDasm, you can view the
manifest information for any managed DLL.
Global Assembly Cache (GAC)
Each computer on which the Common Language Runtime is installed
has a machine-wide code cache called the 'Global Assembly Cache'.
GAC is a folder in Windows directory to store the .NET assemblies
that are specifically designated to be shared by all applications
executed on a system. Assemblies can be shared among multiple
applications on the machine by registering them in global Assembly
cache(GAC).

The GAC is automatically installed with the .NET runtime. The global
assembly cache is located in 'Windows/WinNT' directory and inherits
the directory's access control list that administrators have used to
protect the folder.

The approach of having a specially controlled central repository


addresses the shared library concept and helps to avoid pitfalls of
other solutions that lead to drawbacks like DLL hell.

The Global Assembly Cache Tool (Gacutil.exe), that allows you to


view and manipulate the contents of the Global Assembly Cache.

Where is GAC (Global Assembly Cache) located?

GAC is located in %windir%\assembly (for example,


C:\WINDOWS\assembly) and it is a shared repository of libraries.

How to view the Contents of the Global Assembly Cache (GAC)?

At the Visual Studio command prompt, type the following


command:

gacutil -l or gacutil /l

What is a Satellite Assembly?


A .NET Framework assembly containing resources specific to a given
language. Using satellite assemblies, you can place the resources
for different languages in different assemblies, and the correct
assembly is loaded into memory only if the user selects to view the
application in that language. In general, assemblies should contain
culture-neutral resources. If you want to localize your assembly (for
example use different strings for different locales) you should use
satellite assemblies.

Use the Assembly Linker (Al.exe) to compile .resources files into


satellite assemblies. Al.exe creates an assembly from the .resources
files that you specify. By definition, satellite assemblies can only
contain resources. They cannot contain any executable code.

Net Assembly Contents


A .NET static assembly can consist of following elements:

a) Assembly Manifest - The Metadata that describes the assembly


and its contents

b) Type Metadata - Defines all types, their properties and methods.

c) MSIL - Microsoft intermediate language

d) A set of Resources - All other resources like icons, images etc.

Only the assembly manifest is required, but either types or


resources are needed to give the assembly in any meaningful
functionality.

Private Assembly and Shared Assembly


A private assembly is an assembly that is available to particular
application where they are kept, and a Shared Assembly is a public
assembly that is shared by multiple applications. That means, a
Private Assembly cannot be references outside the scope of the
folder where they are kept and a Shared Assembly is one that can
be referenced by more than one application.

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


for this purpose by giving it a cryptographically strong name . By
contrast, a private assembly name need only be unique within the
application that uses it.

The classes that ship with the .NET Framework are all built as
shared assemblies.

What is .Net Strong Name


Strong name consists of an Assemblys identity, that means the
Assemblies can be assigned a cryptographic signature. The strong
name guarantees the integrity of the assembly which prevents
someone from taking over the name of the assembly.

Strong Name includes the name of the .net assembly, version


number, culture identity, and a public key token. It is generated
from an assembly file using the corresponding private key. Strong
names guarantee name uniqueness by relying on unique key pairs.

To create a key pair

At the command prompt, type the following command:

sn -k fileName

In this command, file name is the name of the output file containing
the key pair.

Microsoft .Net Namespaces


Namespaces are the way to organize .NET Framework Class
Libraryinto a logical grouping according to their functionality,
usability as well as category they should belong to, or we can
say Namespacesare logical grouping of types for the purpose of
identification.

The .NET Framework Class Library (FCL ) is a large collection of


thousands of Classes. These Classes are organized in a hierarchical
tree. The System Namespaces is the root for types in the .NET
Framework. We can uniquely identify any Class in the .NET
Framework Class Library (FCL ) by using the full Namespaces of the
class .In .Net languages every program is created with a default
Namespaces . Programmers can also create their own Namespaces
in .Net languages.

Net Application Domain


An application domain is a virtual process and is used to isolate
applications from one another. Each application domain has their
own virtual address space which scopes the resources for the
application domain using that address space.

Each application running within its main process boundaries and its
application domain boundaries. All objects created within the same
application scope are created within the same application domain.
Multiple application domains can exist in a single operating system
process. An application running inside one application domain
cannot directly access the code running inside another application
domain.

System.AppDomain is the main class you can use to deal with


application domains.

Net Code Access Security


The .NET Security Model provides code access permissions and code
identity permissions. Code Access Security is the part of the .NET
security model that determines whether or not the code is allowed
to run, and what resources it can use when it is running. Code
Access Security policy uses evidence to help grant the right
permissions to the right assembly.
An administrator can configure Code Access Security policy to
restrict the resource types that code can access and the other
privileged operations it can perform. Code Access Security allows
code to be trusted to varying degrees depending on where the code
originates and on other aspects of the code's identity. Code Access
Security can also help minimize the damage that can result from
security vulnerabilities in your code.

Net Garbage Collection


The .Net Framework provides a new mechanism for releasing
unreferenced objects from the memory (that is we no longer needed
that objects in the program) ,this process is called Garbage
Collection (GC). When a program creates an Object, the Object
takes up the memory. Later when the program has no more
references to that Object, the Object's memory becomes
unreachable, but it is not immediately freed. The Garbage Collection
checks to see if there are any Objects in the heap that are no longer
being used by the application. If such Objects exist, then the
memory used by these Objects can be reclaimed. So these
unreferenced Objects should be removed from memory , then the
other new Objects you create can find a place in the Heap.

The reclaimed Objects have to be Finalized later. Finalization allows


a resource to clean up after itself when it is being collected. This
releasing of unreferenced Objects is happening automatically in .Net
languages by the Garbage Collector (GC). The programming
languages like C++, programmers are responsible for allocating
memory for Objects they created in the application and reclaiming
the memory when that Object is no longer needed for the program.
In .Net languages there is a facility that we can call Garbage
Collector (GC) explicitly in the program by calling
System.GC.Collect.

.Net Threading
Thread in computer science means a sequence of execution
instructions that can run independently , that is a single flow of
execution in a process. Thread is like a process, at least one thread
exists within each process. Single Thread (normal programs) in
computer science means that only one task can execute and at the
same time the other tasks have to wait for the completion of the
current task like in a queue. Single thread resulted in systems idle
time and application performance.

Multithreading allows multiple process to execute concurrently


within a single program .That is more than one task in a program
can execute at the same time and each thread run independently of
its own. If multiple threads can exist within a process, typically
share the state information of a process, and share memory and
other resources directly. Each thread maintains exception handlers,
a scheduling priority, and a set of structures the system uses to
save the thread context until it is scheduled.

In multiple threaded programming we can use system's idle time,


so it leads improved application performance . Also we can set
priority in each Threads . Threads with higher priority are executed
in preference to threads with lower priority. It is recommended that
you use as few threads as possible, thereby minimizing the use of
Operating System resources . Check the following links to see how
Multi Threaded applications works in VB.NET .

1. Multithreaded Socket Programming

2. Multi Threaded Chat Server Program

VB.NET Collections
Visual Basic supports a number of data structures called Collections
that holds data in different ways for flexible operations. The
important data structures in the Collection Classes
are ArrayList , HashTable , Stack , Queue etc. From the following
chapters you can see how to manage these data structures in your
visual Basic.net programs.
How to VB.NET ArrayList
ArrayList is one of the most flexible data structure from VB.NET
Collections. With the Array list you can add elements to your array
dynamically and it accepts null as a valid value and also allows
duplicate elements. Normally Collection class allow you to access an
item using either a numeric index or a String key, but ArrayList
allows only a numeric index. ArrayList is flexible because we can
add items without any size information.

Important functions from ArrayList Object

Add : Add Items in an ArrayList

Insert : Insert Items to a specified position in an ArrayList

Remove : Remove an Item from ArrayList

RemoveAt: remove an item from a specified position

Sort : Sort Items in an ArrayList

How to add Items in an ArrayList ?

Syntax : ArrayList.add(Item)

Item : The Item to be add the ArrayList

Dim ItemList As New ArrayList()

ItemList.Add("Item4")

How to Insert Items in an ArrayList ?

Syntax : ArrayList.insert(index,item)

index : The position of the item in an ArrayList


Item : The Item to be add the ArrayList

ItemList.Insert(3, "item6")

How to remove an item from arrayList ?

Syntax : ArrayList.Remove(item)

Item : The Item to be add the ArrayList

ItemList.Remove("item2")

How to remove an item in a specified position from an


ArrayList ?

Syntax : ArrayList.RemoveAt(index)

index : the position of an item to remove from an ArrayList

ItemList.RemoveAt(2)

How to sort ArrayList ?

Syntax : ArrayListSort()

From the following Visual Basic source code you can see some
important operations from an ArrayList Object
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim ItemList As New ArrayList()
ItemList.Add("Item4")
ItemList.Add("Item5")
ItemList.Add("Item2")
ItemList.Add("Item1")
ItemList.Add("Item3")
MsgBox("Shows Added Items")
For i = 0 To ItemList.Count - 1
MsgBox(ItemList.Item(i))
Next
'insert an item
ItemList.Insert(3, "Item6")
'sort itemms in an arraylist
ItemList.Sort()
'remove an item
ItemList.Remove("Item1")
'remove item from a specified index
ItemList.RemoveAt(3)
MsgBox("Shows final Items the ArrayList")
For i = 0 To ItemList.Count - 1
MsgBox(ItemList.Item(i))
Next
End Sub
End Class

How to VB.Net HashTable


HashTable stores a Key Value pair type collection of data . We can
retrive items from hashTable to provide the key . Both key and
value are Objects.

The common functions using in Hashtable are :

Add : To add a pair of value in HashTable

Syntax : HashTable.Add(Key,Value)

Key : The Key value

Value : The value of corrosponding key

ContainsKey : Check if a specified key exist or not

Synatx : HashTable.ContainsKey(key)

Key : The Key value for search in HahTable

ContainsValue : Check the specified Value exist in HashTable

Synatx : HashTable.ContainsValue(Value)

Value : Search the specified Value in HashTable

Remove : Remove the specified Key and corrosponding Value

Syntax : HashTable.Remove(Key)
Key : The argument key of deleting pairs

The following source code shows all important operations in a


HashTable
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim weeks As New Hashtable
Dim day As DictionaryEntry
weeks.Add("1", "Sun")
weeks.Add("2", "Mon")
weeks.Add("3", "Tue")
weeks.Add("4", "Wed")
weeks.Add("5", "Thu")
weeks.Add("6", "Fri")
weeks.Add("7", "Sat")
'Display a single Item
MsgBox(weeks.Item("5"))
'Search an Item
If weeks.ContainsValue("Tue") Then
MsgBox("Find")
Else
MsgBox("Not find")
End If
'remove an Item
weeks.Remove("3")
'Display all key value pairs
For Each day In weeks
MsgBox(day.Key " -- " day.Value)
Next
End Sub
End Class

How to VB.Net Stack


Stack is one of another easy to use VB.NET Collections . Stack
follows the push-pop operations, that is we can Push Items into
Stack and Pop it later also it follows the Last In First Out (LIFO)
system. That is we can push the items into a stack and get it in
reverse order. Stack returns the last item first.

Commonly used methods :

Push : Add (Push) an item in the stack datastructure


Syntax : Stack.Push(Object)

Object : The item to be inserted.

Pop : Pop return the item last Item to insert in stack

Syntax : Stack.Pop()

Return : The last object in the Stack

Contains : Check the object contains in the stack

Syntax : Stack.Contains(Object)

Object : The specified Object to be seach

The following VB.NET Source code shows some of commonly used


functions :
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim stackTable As New Stack
stackTable.Push("Sun")
stackTable.Push("Mon")
stackTable.Push("Tue")
stackTable.Push("Wed")
stackTable.Push("Thu")
stackTable.Push("Fri")
stackTable.Push("Sat")
If stackTable.Contains("Wed") Then
MsgBox(stackTable.Pop())
Else
MsgBox("not exist")
End If
End Sub
End Class

How to VB.Net Queue


The Queue is another adtastructure from VB.NET Collections .
Queue works like First In First Out method and the item added first
in the Queue is first get out from Queue. We can Enqueue (add)
items in Queue and we can Dequeue (remove from Queue ) or we
can Peek (that is get the reference of first item added in Queue )
the item from Queue.

The commonly using functions are follows :

Enqueue : Add an Item in Queue

Syntax : Stack.Enqueue(Object)

Object : The item to add in Queue

Dequeue : Remove the oldest item from Queue (we dont get
the item later)

Syntax : Stack.Dequeue()

Returns : Remove the oldest item and return.

Peek : Get the reference of the oldest item (it is not removed
permenantly)

Syntax : Stack.Peek()

returns : Get the reference of the oldest item in the Queue

The following VB.NET Source code shows some of commonly used


functions :
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles Button1.Click
Dim queueList As New Queue
queueList.Enqueue("Sun")
queueList.Enqueue("Mon")
queueList.Enqueue("Tue")
queueList.Enqueue("Wed")
queueList.Enqueue("Thu")
queueList.Enqueue("fri")
queueList.Enqueue("Sat")
MsgBox(queueList.Dequeue())
MsgBox(queueList.Peek())
If queueList.Contains("Sun") Then
MsgBox("Contains Sun ")
Else
MsgBox("Not Contains Sun ")
End If
End Sub
End Class

How to VB.Net Arrays


Arrays are using for store similar data types grouping as a single
unit. It is a fixed collection of same data type that are stored
contiguously and that are accessible by an index We specify their
length and we can initialize arrays with data. We can
access Arrayelements by its numeric index.

Integer Array

Declaring and Initializing an Integer Array

Dim array As Integer() = New Integer(3) {}

array(0) = 10
array(1) = 20
array(2) = 30
array(3) = 40

In the above code we declare an Integer Array of four elements and


assign the value to array index . That means we assign values to
array index 0-4.

We can retrieve these values from array by using a for loop.

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim array As Integer() = New Integer(3) {}
array(0) = 10
array(1) = 20
array(2) = 30
array(3) = 40
For i As Integer = 0 To array.Length - 1
MessageBox.Show(array(i))
Next
End Sub
End Class

We can declare and initialize an array in one statement.

Dim array As Integer() = New Integer() {10, 20, 30, 40}

Note that in the above code we did not specify the length of the
array so the compiler will do it for us.

How to find the length of an Array ?

array.Length

We can use array.Length to find the length of an Array.

String Array

Declaring and Initializing a String Array

Dim week(6) As String

The above Vb.Net statements means that , an Array named as week


declared as a String type and it can have the capability of seven
String type values.

week(0) = "Sunday"

week(1) = "Monday"

In the above statement , we initialize the values to the String


Array.week(0) = "Sunday" means , we initialize the first value of
Array as "Sunday" ,

Dim weekName as String = week(1)


We can access the Arrays elements by providing its numerical
index, the above statement we access the second value from the
week Array.

In the following program , we declare an Array "week" capability of


seven String values and assigns the seven values as days in a week
. Next step is to retrieve the elements of the Array using a For loop.
For finding the end of an Array we used the Length function of Array
Object.

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim week(6) As String
week(0) = "Sunday"
week(1) = "Monday"
week(2) = "Tuesday"
week(3) = "Wednesday"
week(4) = "Thursday"
week(5) = "Friday"
week(6) = "Saturday"
For i = 0 To week.Length - 1
MsgBox(week(i))
Next
End Sub
End Class

How to resize an array ?

An array can be resized with Array.Resize < T > Method , that


means We make an array bigger or smaller. Array.Resize < T >
Method Changes the number of elements of a one-dimensional
array to the specified new size.

Array.Resize < T > - T is the type of the elements of the array.

This method should be used with only one dimensional Array. This
method allocates a new array with the specified size, copies
elements from the old array to the new one, and then replaces the
old array with the new one.

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim sArray As Char() = New Char(4) {}
sArray(0) = "A"
sArray(1) = "B"
sArray(2) = "C"
sArray(3) = "D"
sArray(4) = "E"
For i As Integer = 0 To sArray.Length - 1
MessageBox.Show(sArray(i).ToString())
Next
Array.Resize(sArray, 3)
For i As Integer = 0 To sArray.Length - 1
MessageBox.Show(sArray(i).ToString())
Next
End Sub
End Class

Array.Resize(sArray, 3)

In the above code we resize the array to 3 elements.

How to Use ForEach loop with Arrays ?


Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim array As Integer() = {10, 30, 50}
'array declaration
For Each element As Integer In array
MsgBox(element)
Next
End Sub
End Class

Array Sort

You can sort the arrays in ascending order as well as


descending . We can use Array.Sort method for sorts
the elements in a one-dimensional array. Also we can
use Array.Reverse method for reverses the sequence
of the elements in the entire one-dimensional Array.
Click the following link to see .... How to sort VB.Net
Arrays

How to Create an Array with different data types

You can create an array with elements of different data types when
declare the array as Object. Since System.Object is the base class
of all other types, an item in an array of Objects can have a
reference to any other type of object. More about.... Multiple data
types in an Array - VB.Net

System.Array.CopyTo and System.Array.Clone()

The System.Array.CopyTo method copies the elements into another


pre-existing array starting from a given index. The
System.Array.Clone() method returns a new array object, which
means that the destination array need not exist yet since a new one
is created from scratch with containing all the elements in the
original array. More about the difference between
.... System.Array.CopyTo and System.Array.Clone()

How to check if a value exists in an array ?

The following program shows how to find a specified value from an


Array.

How to VB.Net Dyanamic Array


Dynamic Arrays can resize the capability of the Array at runtime
.when you are in a situation that you do not know exactly the
number of elements to store in array while you making the
program. In that situations we are using Dynamic Array .

Initial declaration

Dim scores() As Integer

Resizing

ReDim scores(1)

If you want to keep the existing items in the Array , you can use the
keyword Preserve .

ReDim Preserve scores(2)

In this case the Array dynamically allocate one more String value
and keep the existing values.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim scores() As Integer

ReDim scores(1)
scores(0) = 100
scores(1) = 200

For i = 0 To scores.Length - 1
MsgBox(scores(i))
Next

ReDim Preserve scores(2)

scores(2) = 300

For i = 0 To scores.Length - 1
MsgBox(scores(i))
Next
End Sub
End Class

How to VB.Net NameValueCollection


NameValueCollection is used to store data like Name, Value
format. It is very similar to Vb.Net HashTable, HashTable also stores
data in Key , value format . NameValueCollection can hold more
than one value for a corresponding Key.

Adding new pairs

Add(ByVal name As String, ByVal value As String)

Add("High","80")

Get the value of corresponding Key

GetValues(ByVal name As String) As String()

String values() = GetValues("High")


Imports System.Collections.Specialized
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim markStatus As New NameValueCollection
Dim key As String
Dim values() As String

markStatus.Add("Very High", "80")


markStatus.Add("High", "60")
markStatus.Add("medium", "50")
markStatus.Add("Pass", "40")

For Each key In markStatus.Keys


values = markStatus.GetValues(key)
For Each value As String In values
MsgBox(key & " - " & value)
Next value
Next key

End Sub
End Class

How to use VB.NET List


VB.NET List examples

Generic lists were introduced with .Net 2.0 and are


the way to go. List is a generic implementation of
ArrayList. List can store only one type of objects, that
type supplied as its generic parameter. List class is a
collection and defined in the
System.Collections.Generic namespace and it
provides the methods and properties like other
Collection classes such as add, insert, remove, search etc.

To use List(Of T), however, you have to understand how to


implement the many methods that the .NET Framework provides

List(Of T)

The parameter T is the type of elements in the list.

How to add items in List ?

Add integer values in the List


Dim iList As New List(Of Integer)()
iList.Add(2)
iList.Add(3)
iList.Add(5)
iList.Add(7)

Add string values in the List

Dim numbers As New List(Of String)()


numbers.Add("One")
numbers.Add("Two")
numbers.Add("Three")

How to count number of items exists in a List ?

List.Count property gives you the number of items exists in List

numbers.Count

How to retrieve items from List ?

You can retrieve items from List collection by using for loops.

foreach loop

For Each number As String In numbers


MessageBox.Show(number)
Next

for loop

For i As Integer = 0 To numbers.Count - 1


MessageBox.Show(numbers(i))
Next

How to insert an item in the List ?

You can use insert(index,item) method to insert an in the specified


index.

numbers.Insert(1, "zero")
In the above code the number "zero" is inserted in the index
position 1.

How to remove an item from List collection?

List.Remove() can use to remove item from List.

numbers.Remove("zero");

How to check if an item exist in the List ?

You can use List.Contains() method to check an item exists in the


List

if (numbers.Contains("Two"))
{
MessageBox.Show("Number Two exist in the list");
}

How to copy an Array to a List ?

Dim strArr As String() = New String(2) {}


strArr(0) = "Red"
strArr(1) = "Blue"
strArr(2) = "Green"
//here to copy array to List
Dim arrlist As New List(Of String)(strArr)

Finally clear method remove all the items from List collection.

arrlist.Clear()

Difference between list and dictionary in VB.Net

In VB.Net applications both lists and dictionaries are used to store


collections of data. List (ICollection ) is simply a set of items and
Dictionary(IDictionary) is a set of key-value pairs. The essential
difference therefore is in how the containers are indexed data in
your VB.Net application. If you want to know more details.....What
is the difference between list and dictionary in VB.Net?
The following VB.Net program shows the implementation of the
above functionalities in List collection.
Public Class Form1

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


System.EventArgs) Handles Button1.Click
Dim numbers As New List(Of String)()

'add items in a List collection


numbers.Add("One")
numbers.Add("Two")
numbers.Add("Three")

'insert an item in the list


numbers.Insert(1, "Zero")

'retrieve items using foreach loop


For Each number As String In numbers
MessageBox.Show(number)
Next

'remove an item from list


numbers.Remove("Zero")

'retrieve items using for loop


For i As Integer = 0 To numbers.Count - 1
MessageBox.Show(numbers(i))
Next

If numbers.Contains("Two") Then
MessageBox.Show("Number two exist in the list")
Else
MessageBox.Show("Not exist")
End If

'copy array to list


Dim strArr As String() = New String(2) {}
strArr(0) = "Red"
strArr(1) = "Blue"
strArr(2) = "Green"
Dim arrlist As New List(Of String)(strArr)

For Each str As String In strArr


MessageBox.Show(str)
Next

'call clear method


arrlist.Clear()

MessageBox.Show(arrlist.Count.ToString())

End Sub
End Class
Dictionary in vb.net
How to VB.Net Dictionary

A Dictionary class is a data structure that represents a collection of


keys and values pair of data. Each item is a combination of a key
and a value. ( key-value pair)

Syntax:

Parameters :

TKey - The type of the keys in the dictionary.


TValue - The type of the values in the dictionary.

e.g.

Dim dict As New Dictionary(Of String, Integer)()

Adding Values to Dictionary

Add method in Dictionary takes two parameters, one for the key
and one for the value.

Syntax:

public void Add(TKey key,TValue value)

e.g.

dictionary.Add("dozen",12)

Key in a Dictionary should not be null, but a value can be, if TValue
is a reference type.

Dim dict As New Dictionary(Of String, Integer)()


dict.Add("one", 1)
dict.Add("two", 2)
dict.Add("three", 3)
dict.Add("four", 4)

Retrieve Key-Value pair from Dictionary

We can retrieve values from Dictionary using foreach loop

For Each pair As KeyValuePair(Of String, Integer) In dict


MsgBox(pair.Key & " - " & pair.Value)
Next

Search for a Key

We can search a Key in Dictionary by using the ContainsKey method


to test whether a key exists or not. ContainsKey computes the
hashcode for its argument and checks the internal structures in the
Dictionary.

If dict.ContainsKey("four") = True Then


MessageBox.Show(dict("four").ToString())
Else
MessageBox.Show("Key does not exist")
End If

Iterate over a Dictionary

There are many different ways to iterate over a Dictionary in


VB.Net. From the following link you can see in detail .... How to
Iterate over a Dictionary

Dictionary Versus HashTable

Dictionary is a generic type, Hashtable is not. That


means you get type safety with Dictionary, because
you can't insert any random object into it, and you
don't have to cast the values you take out. Since both
Dictionary and Hashtable are internally hashtables, so fast access to
many-item data according to key, also both need immutable and
unique keys. More about.... Dictionary Vs HashTable
Dictionary Versus List

Both lists and dictionaries are used to store


collections of data. The Dictionary is based on a
hash table, that means it uses a hash lookup, which
is a rather efficient algorithm to look up things, on
the other hand, a list you have to go element by element until it
finds the result from beginning to the result each time. More
about.... Dictionary vs List

Following vb.net program is a full source code of adding and


retrieving key values pairs in Dictionary

Das könnte Ihnen auch gefallen