0% found this document useful (0 votes)
264 views

Lesson

This document provides an overview of VB.NET, including what it is, its features, advantages, and disadvantages. VB.NET is an object-oriented programming language that builds applications on the .NET framework. It supports concepts like abstraction, encapsulation, inheritance and polymorphism. Applications built in VB.NET are reliable, scalable and can run on Windows, Linux and Mac OS. The .NET framework provides a common language runtime and class libraries that allow applications created in different languages to work together.

Uploaded by

Lapa Etienne
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
264 views

Lesson

This document provides an overview of VB.NET, including what it is, its features, advantages, and disadvantages. VB.NET is an object-oriented programming language that builds applications on the .NET framework. It supports concepts like abstraction, encapsulation, inheritance and polymorphism. Applications built in VB.NET are reliable, scalable and can run on Windows, Linux and Mac OS. The .NET framework provides a common language runtime and class libraries that allow applications created in different languages to work together.

Uploaded by

Lapa Etienne
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 329

VB.

NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

VB.NET Tutorial
VB.NET is a simple, multi-paradigm object-oriented programming language designed to create a wide
range of Windows, Web, and mobile applications built on the .NET Framework. Our VB.NET
Tutorial covers all the basic and advanced concepts of VB.NET such as features, strings, arrays,
program flow control, file and exception handling, events, forms, buttons and more.

What is VB.NET?
The VB.NET stands for Visual Basic. Network Enabled Technologies. It is a simple, high-level, object-
oriented programming language developed by Microsoft in 2002. It is a successor of Visual Basic 6.0, that
is implemented on the Microsoft .NET framework. Furthermore, it supports the OOPs concept, such as
abstraction, encapsulation, inheritance, and polymorphism. Therefore, everything in the VB.NET language is
an object, including all primitive data types (Integer, String, char, long, short, Boolean, etc.), user-defined
data types, events, and all objects that inherit from its base class. It is not a case sensitive language,
whereas, C++, Java, and C# are case sensitive language.

Applications built using the VB.NET language are very reliable and scalable, relying on the .NET Framework
to access all libraries that help to execute a VB.NET program. With this language, you can develop a fully
object-oriented application that is similar to an application created through another language such as C+
+, Java, or C#. In addition, applications or programs of VB.NET are not only running on the window
operating system but can also run on Linux or Mac OS.

The VB.NET language is designed in such a way that any new beginner or novice and the advanced
programmer can quickly develop a simple, secure, robust, high performance of web, windows, console, and
mobile application running on .NET Framework.

VB.NET Features
As we know, it is a high-level programming language with many features to develop a secure and robust
application. These are the following features that make it the most popular programming language.

o It is an object-oriented programming language that follows various oops concepts such as


abstraction, encapsulation, inheritance, and many more. It means that everything in VB.NET
programming will be treated as an object.
o This language is used to design user interfaces for window, mobile, and web-based applications.
o It supports a rapid application development tool kit. In which a developer does not need to write all
the codes as it can get various code automatically from its libraries. For example, when we create a
form in Visual basic.net, it automatically calls events of various form in that class.
o It is not a case sensitive language like other languages such as C++, java, etc.
o It supports Boolean condition for decision making in programming.
o It also supports the multithreading concept, in which you can do multiple tasks at the same time.
o It provides simple events management in .NET application.
o A Window Form enables us to inherit all existing functionality of form that can be used to create a
new form. So, in this way, it reduced the code complexity.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

o It uses an external object as a reference that can be used in a VB.NET application.


o Automatic initialized a garbage collection.
o It follows a structured and extensible programming language for error detection and recovery.
o Conditional compilation and easy to use generic classes.
o It is useful to develop web, window, and mobile applications.

Advantages of VB.NET
o The VB.NET executes a program in such a way that runs under CLR (Common Language Runtime),
creating a robust, stable, and secure application.
o It is a pure object-oriented programming language based on objects and classes. However, these
features are not available in the previous version of Visual Basic 6. That's why Microsoft launched
VB.NET language.
o Using the Visual Studio IDE, you can develop a small program that works faster, with a large desktop
and web application.
o The .NET Framework is a software framework that has a large collection of libraries, which helps in
developing more robust applications.
o It uses drop and drag elements to create web forms in .NET applications.
o However, a Visual Basic .NET allows to connect one application to another application that created
in the same language to run on the .NET framework.
o A VB.NET can automatically structure your code.
o The Visual Basic .NET language is also used to transfer data between different layers of the .NET
architecture such that data is passed as simple text strings.
o It uses a new concept of error handling in the Visual Basic .NET Framework. The new structure is the
try, catch, and finally method used to handle exceptions as a unit. In addition, it allows appropriate
action to be taken at the place where it encountered an error. In this way, it discourages the use of
the ON ERROR GOTO statement in .NET programming.

Disadvantages of VB.NET
1. The VB.NET programming language is unable to handle pointers directly. Because in this language,
it requires a lot of programming, and it is not easy to manage every address by a pointer.
Furthermore, additional coding takes extra CPU cycles, that increases the processing time. It shows
the slowness of the VB.NET application.
2. The VB.NET programming is easy to learn, that increases a large competition between the
programmers to apply the same employment or project in VB.NET. Thus, it reduces a secure job in
the programming field as a VB.NET developer.
3. It uses an Intermediate Language (IL) compilation that can be easily decompiled (reverse
engineered), but there is nothing that can prevent an application from disintegrating.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

4. Just-In-Time (JIT) compiler: It is the process through which a computer can interpret IL (intermediate
language) compilation and is also required to run your application. It means that the target
computer needs a JIT compiler to interpret a source program in IL, and this interpretation requires
an additional CPU cycle that degrades the performance of an application.
5. It contains a large collection of libraries for the JIT compiler that helps to interpret an application.
These large libraries hold a vast space in our system that takes more computing time.

Introduction to .NET Framework


The .NET Framework is a software development platform that was introduced by Microsoft in the late
1990 under the NGWS. On 13 February 2002, Microsoft launched the first version of the .NET Framework,
referred to as the .NET Framework 1.0.

In this section, we will understand the .NET Framework, characteristics, components, and its versions.

What is .NET Framework


It is a virtual machine that provide a common platform to run an application that was built using the
different language such as C#, VB.NET, Visual Basic, etc. It is also used to create a form based, console-
based, mobile and web-based application or services that are available in Microsoft environment.
Furthermore, the .NET framework is a pure object oriented, that similar to the Java language. But it is not a
platform independent as the Java. So, its application runs only to the windows platform.

The main objective of this framework is to develop an application that can run on the windows platform.
The current version of the .Net framework is 4.8.

Note: The .NET Framework is not only a language, but it is also a software and language neutral platform.

Components of .NET Framework


There are following components of .NET Framework:

1. CLR (Common Language Runtime)


2. CTS (Common Type System)
3. BCL (Base Class Library)
4. CLS (Common Language Specification)
5. FCL (Framework Class Library)
6. .NET Assemblies
7. XML Web Services
8. Window Services

CLR (common language runtime)


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
It is an important part of a .NET framework that works like a virtual component of the .NET Framework to
executes the different languages program like c#, Visual Basic, etc. A CLR also helps to convert a source
code into the byte code, and this byte code is known as CIL (Common Intermediate Language) or MSIL
(Microsoft Intermediate Language). After converting into a byte code, a CLR uses a JIT compiler at run time
that helps to convert a CIL or MSIL code into the machine or native code.

CTS (Common Type System)

It specifies a standard that represent what type of data and value can be defined and managed in
computer memory at runtime. A CTS ensures that programming data defined in various languages should
beinteract with each other to share information. For example, in C# we define data type as int, while in
VB.NET we define integer as a data type.

BCL (Base Class Library)

The base class library has a rich collection of libraries features and functions that help to implement many
programming languages in the .NET Framework, such as C #, F #, Visual C ++, and more. Furthermore, BCL
divides into two parts:

1. User defined class library

o Assemblies - It is the collection of small parts of deployment an application's part. It contains
either the DLL (Dynamic Link Library) or exe (Executable) file.

1. In LL, it uses code reusability, whereas in exe it contains only output file/ or
application.
2. DLL file can't be open, whereas exe file can be open.
3. DLL file can't be run individually, whereas in exe, it can run individually.
4. In DLL file, there is no main method, whereas exe file has main method.

2. Predefined class library

o Namespace - It is the collection of predefined class and method that present in .Net. In other
languages such as, C we used header files, in java we used package similarly we used "using
system" in .NET, where using is a keyword and system is a namespace.

CLS (Common language Specification)

It is a subset of common type system (CTS) that defines a set of rules and regulations which should be
followed by every language that comes under the .net framework. In other words, a CLS language should
be cross-language integration or interoperability. For example, in C# and VB.NET language, the C#
language terminate each statement with semicolon, whereas in VB.NET it is not end with semicolon, and
when these statements execute in .NET Framework, it provides a common platform to interact and share
information with each other.

Microsoft .NET Assemblies


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
A .NET assembly is the main building block of the .NET Framework. It is a small unit of code that contains a
logical compiled code in the Common Language infrastructure (CLI), which is used for deployment, security
and versioning. It defines in two parts (process) DLL and library (exe) assemblies. When the .NET program is
compiled, it generates a metadata with Microsoft Intermediate Language, which is stored in a file called
Assembly.

FCL (Framework Class Library)

It provides the various system functionality in the .NET Framework, that includes classes, interfaces and
data types, etc. to create multiple functions and different types of application such as desktop, web, mobile
application, etc. In other words, it can be defined as, it provides a base on which various applications,
controls and components are built in .NET Framework.

Key Components of FCL

1. Object type
2. Implementation of data structure
3. Base data types
4. Garbage collection
5. Security and database connectivity
6. Creating common platform for window and web-based application

Characteristics of .NET Framework

1. CLR (Common Language Runtime)


2. Namespace - Predefined class and function
3. Metadata and Assemblies
4. Application domains
5. It helps to configure and deploy the .net application
6. It provides form and web-based services
7. NET and ASP.NET AJAX
8. LINQ
9. Security and Portability
10. Interoperability
11. It provides multiple environments for developing an application

Versions of .NET Framework

1. On 13 February 2002, Microsoft launched first version of .Net framework 1.0.


2. The second version 2.0 of .net framework was launched on 22 January 2006.
3. Third version 3.0 of .Net framework was released on 21 November 2006.
4. A .Net framework version 3.5 was released on 19 November 2007.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

5. Version 4.0 of .Net framework was released on 29 September 2008


6. Version 4.5 of .Net framework was released on 15 August 2012.
7. .Net framework 4.5.1 version was announced on 17 October 2013
8. On 5 May 2014, a 4.5.2 version of .Net framework was released.
9. .Net framework 4.6 version was announced on 12 November 2014
10. .Net framework 4.6.1 version was released on 30 October 2015
11. .Net framework 4.6.2 version was announced on March 30, 2016
12. .Net framework 4.7 version was announced on April 5, 2017
13. .Net framework 4.7.1 version was announced on October 17, 2017
14. Version 4.7.2 of .Net framework was released on 30 April 2018.
15. And currently we are using .Net framework version 4.8 that was released on 18 April 2019

VB.NET Hello World Program


In the previous topic, we have installed Visual Studio 2019 and created a console-based project with the
name MYConsoleApp1. Now in this project, we will create our Hello world VB.NET program.

A VB.NET define the following structure to create a program:

o Namespace declaration
o Procedure can be multiple
o Define a class or module
o Variables
o The Main procedure
o Statement and Expression
o Comments

Create a Hello_Program.vb file in MYConsoleApp1 project and write the following code:

Hello_Program.vb

1. Imports System 'System is a Namespace  
2. Module Hello_Program  
3.   
4.     Sub Main()  
5.   
6.         Console.WriteLine("Hello, Welcome to the world of VB.NET")  
7.         Console.WriteLine("Press any key to continue...")  
8.         Console.ReadKey()  
9.   
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

10.     End Sub  
11.   
12. End Module  

Let's compile and run the above program by pressing the F5 key, we get the follwoiing output.

Output:

An Alternate method to compile and execute the VB.NET


program
We can also compile and execute the VB.NET program using the Command prompt instead of using the
Visual Studio IDE.

Step 1: After creating and saving the Hello_Program.vb file in the MYConsoleApp1 project, open the
command prompt and execute the commands, as we have shown in the prompt.

In place of MYConsoleApp1you can write your project name.

Step 2: After that, write vbc Hello_Program.vb, as shown below.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 3: If there is no error found at compile-time, it transfers the control in the next line for generating
the Hello_Pogram.exe file.

Step 4: Type Hello_Program to run the program. We get the following output.

Output:

Hello, Welcome to the world of VB.NET.

Now we will understand the basic structure of the VB.NET program:

o In VB.NET programming, the first line of the program is "Import System", where Imports is a
statement that inherit the system namespace. A System is a namespace that contains basic classes,
reference data types, events, attributes, and various inbuilt functions that help to run the program.
o The Second line defines the Module It specifies the VB.NET filename. As we know, VB.NET
language is a completely object-oriented language, so every program must contain a module or
class in which you can write your program that contains data and procedures within the module.

1. Module Module1  
2. End Module  
o You can define more than one procedure in classes and modules. Generally, the procedure contains
executable code to run. A procedure may contain the following function:

o Function
o Operator
o Sub
o Get
o Set
o AddHandler
o RemoveHandler
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

o Every program must contain a Main() method. In VB.NET, there is a Main() method or procedure
that represents the starting point to execute a program, as we have seen in C language, their entry
point is the main() function.
o A comment (') symbol is used to comment on a line that is ignored by the compiler in a program,
and it is a good practice to use comments for a better understanding of the program.
o The Console.WriteLine () is a method of the console class. It is used to print any text or messages in
the application. And the Console.ReadKey () is used to read a single character from the keyboard
back to the Visual Studio IDE.

Create a VB.NET program using Windows Form


If you want to create a new Window-based project in Visual Studio, follow the steps given below:

Step 1. Start the Visual Studio IDE.

Step 2. To create a project, click on File -> choose-> New-> Project

The following window appears on the screen.

Step 3: Select Windows Forms App (.NET Framework) and click on the Next button.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 4: Provide the Project name and location to store the project file using the browse button in Location.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 5: Click on the Create button. The following window appears on the screen.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 6: Now double click on the middle area of Form1.vb (Design) file, it shows the following code.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Form1.vb

1. Public Class Form1  
2.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         MsgBox("Welcome to the JavaTpoint")  
4.     End Sub  
5. End Class  

Step7: Save file as Form1.vb.

Step 8: To compile and run the Form1.vb file, press F5 button or Start button in Visual Studio. It shows the
following output.

VB.NET Keywords
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
A keyword is a reserved word with special meanings in the compiler, whose meaning cannot be changed.
Therefore, these keywords cannot be used as an identifier in VB.NET programming such as class name,
variable, function, module, etc.

In this section, we will understand about the VB.NET identifier, VB.NET comment, and how we can use it
in VB.NET.

There are following reserved keyword available in the VB.NET language.

AddHandler AddressOf Alias And AndAlso As

Boolean ByRef Byte ByVal Call Case

Catch CBool CByte CChar CDate CDbl

CDec Char Cint Class CLng CObj

Const Continue CSByte CShort CSng CStr

CType CUnit CULng CUShort Date Decimal

Declare Default Delegate Dim DirectCast Do

Double Each Else Elseif End End if

Enum Erase Error Event Exit False

Finally For Friend Function Get GetType

GetXML Namespace Global GoTO Handles If Implements

Imports In Inherits Integer Interface Is

isNot Let Lib Like Long Loop

Me Mod Module MustInherit MustOverride MyBase

MyClass Namespace Narrowing New Next Not

Nothing Not Inheritable Not Overridable Object Of On

Operator Option Optional Or OrElse Overloads

Overridable Overrides ParamArray Partial Private Property

Protected Public RaiseEvent ReadOnly ReDim REM

Remove Handler Resume Return SByte Select Set

Shadows Shared Short Single Static Step

Stop String Structure Sub SyncLock Then


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Throw To True Try TryCast TypeOf

UInteger While Widening With WithEvents WhiteOnly

Xor #Else IsReference TimeOfDay Append Auto

Let's create a program to find the area and perimeter of a rectangle in VB.NET.

Rectangle.vb

1. Module Rectangle  
2.     Public Length As Integer  
3.   
4.     Public Breadth As Integer  
5.     Public Sub Dimension()  
6.         Length = 5  
7.         Breadth = 6  
8.     End Sub  
9.     Public Function Area() As Integer  
10.         Area = Length * Breadth  
11.     End Function  
12.     Public Function Pera() As Integer  
13.         Pera = 2 * (Length + Breadth)  
14.     End Function  
15.     Public Sub Display()  
16.         Console.WriteLine(" Length is: {0}", Length)  
17.         Console.WriteLine("Breadth is: {0}", Breadth)  
18.         Console.WriteLine(" Area of Rectangle is: {0}", Area())  
19.         Console.WriteLine(" Perimeter of Rectangle is: {0}", Pera())  
20.     End Sub  
21.     Sub Main()  
22.         Dimension() ' directly call the function in main method  
23.         Area()  
24.         Pera()  ' directly call the function in main method  
25.         Display()  
26.         Console.WriteLine("Press any key to exit...")  
27.         Console.ReadKey()  
28.     End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

29. End Module  

Output:

Length is: 5
Breadth is: 6
Area of Rectangle is: 30
Perimeter of Rectangle is: 22
Press any key to exit...

VB.NET Identifiers
As the name defines, an identifier is used to identify the name of variable, function, class, or any other
user-defined elements in the program. An identifier should be the combination of letter, digit, and
underscore. Still, the first character of the identifier or variable name should start with alphabet letter or
underscore (_) of any length.

There are various rules for identifier in VB.NET, as follows:

1. The first character of an identifier must start with an alphabet or underscore, that could be followed
by any sequence of digits (0-9), letter or underscore.
2. An identifier should not contain any reserved keyword.
3. It should not start with any digit.
4. It should not more than 51 characters.
5. An identifier can contain two underscores, but should not be consecutive.
6. It should not include any commas or white spaces in-between characters.

Generally, identifiers are meaningful names. Some valid identifiers are:

Value, a, rec1, my_data, Marks, num, etc.

Some invalid identifiers are:

5be             : First character should be alphabets or underscore (_)

Class, Shared     : Keyword are not allowed as identifier name.

A# -             : Identifier does not contain any special symbol.

Avg marks             : It should not contain any blank space.

Program.vb

1. Imports System  
2. Module Program ' Identifier' name should be valid  
3.   
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

4.     Public Sub myfunc()  ' function name   
5.         Console.WriteLine("Hello friends..")  
6.     End Sub  
7.   
8.     Sub Main()  
9.         myfunc()  
10.         Console.WriteLine("Nice to meet you...")  
11.         Console.WriteLine("press any key to exit...")  
12.         Console.ReadKey()  
13.     End Sub  
14. End Module  

Let's compile and execute the above program.

Output:

Hello friends...
Nice to meet you...
press any key to exit...

VB.NET Comments
A comment is used to explain the various steps that we have taken in our programming. The compiler
ignores these comment statements because the compiler is not executed or processed in VB.NET.
Therefore, it does not take any place in your compilation code.

In VB.NET, we use ( ' ) symbol to comment a statement.

1. Sub main()  
2. 'Here Console.WriteLine() is used to print a statement.  
3. Console.WriteLine(" Welcome to JavaTpoint")  
4. 'Above statement displays Welcome to JavaTpoint  
5. End Sub  

Circle.vb

1. Imports System   
2. Public Class Circle   
3.   'define the variable  
4.     Dim radius As Integer = 10   
5.     Public Function SetCircle() As Double    
6.             SetCircle = 2 * 3.14 * radius  ' Function is used to return some value  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

7.         End Function  
8.         Public Sub display()         ' create display() sub function to print the message   
9.             Console.Write(" Radius is: {0}", radius)  
10.         Console.WriteLine(" Circumference of Circle: {0}", SetCircle())  
11.     End Sub  
12.     'Shared keyword can be used without creating an object  
13.     Shared Sub Main()   
14.         Dim obj As New Circle()  
15.         obj.SetCircle() 'object reference  
16.         obj.display()  
17.         Console.ReadKey()  
18.     End Sub  
19. End Class  

Now compile and execute the above program.

Output:

Radius is: 10 Circumference of Circle: 62.8


press any key to exit...

Hence, it is the best way to explain every step of VB.NET programming language.

VB.NET Data Type


In VB.NET, data type is used to define the type of a variable or function in a program. Furthermore, the
conversion of one data type to another type using the data conversion function.

A Data Type refers to which type of data or value is assigning to a variable or function so that a variable
can hold a defined data type value. For example, when we declare a variable, we have to tell the compiler
what type of data or value is allocated to different kinds of variables to hold different amounts of space in
computer memory.

Syntax:

1. Dim Variable_Name as DataType  

VariableName: It defines the name of the variable that you assign to store values.

DataType: It represents the name of the data type that you assign to a variable.

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.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Data Types Required Space Value Range

Boolean A Boolean type depends on True or False


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
platform such as 4 bytes in type Object
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 on It accepts Unicode character from 0 to approximately


the implementing platform 2 billion characters.

UInteger 4 bytes The range start from 0 to 4,294,967,295 (unsigned)

ULong 8 bytes The range of ULong start from 0 to


18,446,744,073,709,551,615 (1.8…E + 19) (unsigned)

User-Defined A user-defined data type Each member of the structure has its own data type
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

(structure) depends on the and limits independent of the other members'


implementing platform ranges.

UShort 2 bytes Range from 0 to 65,535 (unsigned)

Let's use the various data types in a VB.NET program.

Data_type.vb

1. Module Data_type  
2.     Sub Main()  
3. ' defining the Data Type to the variables  
4.         Dim b As Byte = 1  
5.         Dim num As Integer = 5  
6.         Dim si As Single  
7.         Dim db As Double  
8.         Dim get_date As Date  
9.         Dim c As Char  
10.         Dim str As String  
11.   
12.         b = 1  
13.         num = 20  
14.         si = 0.12  
15.         db = 2131.787  
16.         get_date = Today  
17.         c = "A"  
18.         str = "Hello Friends..."  
19.   
20.         Console.WriteLine("Welcome to the JavaTpoint")  
21.         Console.WriteLine("Byte is: {0}", b)  
22.         Console.WriteLine("Integer number is: {0}", num)  
23.         Console.WriteLine("Single data type is: {0}", si)  
24.         Console.WriteLine("Double data type is: {0}", db)  
25.         Console.WriteLine("Today is: {0}", get_date)  
26.         Console.WriteLine("Character is: {0}", b)  
27.         Console.WriteLine("String message is: {0}", str)  
28.         Console.ReadKey()  
29.     End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

30. End Module  

Output:

Welcome to the JavaTpoint


Byte is: 1
Integer number is: 20
Single data type is: 0.12
Double data type is: 2131.787
Today is: 31-05-2020 00:00:00
Character is: 1
String message is: Hello Friends...

Type Conversion Functions in VB.NET


The following functions are available for conversion.

1. CBool(expression): It is used to convert an expression into a Boolean data type.


2. CByte(expression): It is used to convert an expression to a Byte data type.
3. CChar(expression): It is used to convert an expression to a Char data type.
4. CDate(expression): It is used to convert an expression to a Date data type.
5. CDbl(expression): It is used to convert an expression into a Double data type.
6. CDec(expression): It is used to convert an expression into a Decimal data type.
7. CInt(expression): It is used to convert an expression to an Integer data type.
8. CLng(expression): It is used to convert an expression to a Long data type.
9. CObj(expression): It is used to convert an expression to an Object data type.
10. CSByte(expression): It is used to convert an expression to an SByte data type.
11. CShort(expression): It is used to convert an expression to a Short data type.
12. CSng(expression): It is used to convert an expression into a Single data type.
13. CStr(expression): It is used to convert an expression into a String data type.
14. CUInt(expression): It is used to convert an expression to a UInt data type.
15. CULng(expression): It is used to convert an expression to a ULng data type.
16. CUShort(expression): It is used to convert an expression into a UShort data type.

In the following, program we have performed different conversion.

DB_Conversion.vb

1. Option Strict On   
2. Module DB_Conversion  
3.     Sub Main()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

4.     'defining the Data type conversion  
5.         Dim dblData As Double  
6.         dblData = 5.78  
7.         Dim A, B As Char  
8.         Dim bool As Boolean = True  
9.         Dim x, Z, B_int As Integer  
10.         A = "A"  
11.         B = "B"  
12.         B_int = AscW(B)  
13.   
14.         Console.WriteLine(" Ascii value of B is {0}", B_int)  
15.   
16.         x = 1  
17.         Z = AscW(A)  
18.         Z = Z + x  
19.         Console.WriteLine("String to integer {0}", Z)  
20.         Console.WriteLine("Boolean value is : {0}", CStr(bool))  
21.         Dim num, intData As Integer  
22.   
23.         num = CInt(dblData)  
24.         intData = CType(dblData, Integer)  
25.         Console.WriteLine(" Explicit conversion of Data type " & Str(intData))  
26.         Console.WriteLine(" Value of Double is: {0}", dblData)  
27.         Console.WriteLine("Double to Integer: {0}", num)  
28.         Console.ReadKey()  
29.     End Sub  
30. End Module  

Output:

Ascii value of B is 66
String to integer 66
Boolean value is: True
Explicit conversion of Data type 6
Value of Double is: 5.78
Double to Integer: 6

VB.NET Variable and Constant


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
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.

What is a 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 it simply requires a variable name and data type followed by a Dim. A Dim is
used in Class, Module, structure, Sub, procedure.

Syntax:

1. 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.

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


e

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:

1. Dim Roll_no As Integer  
2. Dim Emp_name As String  
3. Dim Salary As Double  
4. Dim Emp_id, Stud_id As Integer  
5. 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
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

1. 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:

1. Static name As String  
2. 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:

1. Variable_name = value  

For example:

1. Dim Roll_no As Integer 'declaration of Roll_no    
2. Roll_no = 101 'initialization of Roll_no  
3.   
4. Initialize the Emp_name  
5. Dim Emp_name As String  
6. Emp_name = "David" 'Here Emp_name variable assigned a value of David  
7.   
8. Initialize a Boolean variable  
9. Dim status As Boolean 'Boolean value can be True or False.  
10. status = True 'Initialize status value to True  

We can also initialize a variable at the time of declaration:

1. Dim Roll_no As Integer = 101  
2. Dim Emp_name As String = " Stephen Robert "  

Let's create a program to use different types of variable declaration and initialization in VB.NET.

Variable1.vb

1. Imports System  
2. Module Variable1  
3.     Sub Main()  
4.         'declaration of intData as Integer  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

5.         Dim intData As Integer  
6.         'declaration of charData as Char  
7.         Dim CharData As Char  
8.         'declaration of strData as String  
9.         Dim strData As String  
10.         'declaration of dblData as Double  
11.         Dim dblData As Double  
12.         'declaration of single_data as Single  
13.         Dim single_data As Single  
14.         'Initialization of intData  
15.         intData = 10  
16.         'Initialization of CharData  
17.         CharData = "A"  
18.         'Initialization of strData  
19.         strData = " VB.NET is a Programming Language."  
20.         dblData = 4567.676  
21.        'Initialization of dblData  
22.        'Initialization of single_data  
23.         single_data = 23.08  
24.   
25.         Console.WriteLine(" Value of intData is: {0}", intData)  
26.         Console.WriteLine(" Value of CharData is: {0}", CharData)  
27.         Console.WriteLine(" Value of strData is: {0}", strData)  
28.         Console.WriteLine(" Value of dblData is: {0}", dblData)  
29.         Console.WriteLine(" Value of single_data is: {0}", single_data)  
30.   
31.         Console.WriteLine(" press any key to exit...")  
32.         Console.ReadKey()  
33.     End Sub  
34.   
35. End Module  

Output:

Value of intData is: 10


Value of CharData is: A
Value of strData is: VB.NET is a Programming Language.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
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:

1. Dim name As String  
2. name = Console.ReadLine()  
3. Or name = Console.ReadLine  

Let's create a program that takes input from the user.

User_Data.vb

1. Imports System  
2. Module User_Data  
3.     Sub Main()  
4.         Dim num As Integer  
5.         Dim age As Double  
6.         Dim name As String  
7.         Console.WriteLine("Enter your favourite number")  
8.         ' Console.ReadLine or Console.ReadLine() takes value from the user  
9.         num = Console.ReadLine  
10.         Console.WriteLine(" Enter Your Good name")  
11.         'Read string data from the user  
12.         name = Console.ReadLine  
13.         Console.WriteLine(" Enter your Age")  
14.         age = Console.ReadLine  
15.         Console.WriteLine(" You have entered {0}", num)  
16.         Console.WriteLine(" You have entered {0}", name)  
17.         Console.WriteLine(" You have entered {0}", age)  
18.         Console.ReadKey()  
19.   
20.     End Sub  
21. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Enter your favourite number
7
Enter Your Good name
Alexander
Enter your Age
27.5
You have entered 7
You have entered Alexander
You have entered 27.5

Note: Console.Read and Console.ReadKey() function is used to read a single character from the user.

Lvalues and Rvalues in VB.NET


There are two ways to express the expression value:

Lvalue: It is an lvalue expression that refers to a memory location for storing the address of a variable . An
lvalue is a variable that can appear to the left or right of the assignment operator to hold values.
Furthermore, in comparison to or swapping the variables' values, we can also define the variable on both
sides (left or right-side) of the assignment operator.

Example:

1. Dim num As Integer  
2. Num = 5   
3. Or   
4. Dim num As Integer = 5  

But when we write the following statement, it generates a compile-time error because it is not a valid
statement.

1. Dim x As Integer  
2. 10 = x  

Rvalue: It is an rvalue expression that is used to store a value in some address of memory. An rvalue can
appear only on the right- hand side because it is a value of the variable that defines on the right-hand side.

1. Dim name As String  
2. Name = "Peter" // rvalue define at right side of the assignment operator.  

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.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
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:

1. Const constname As datatype = value  

Item Descriptions
Name

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:

1. Dim Variable_name1 As DataType1, variable_name2 As DataType2, Variable_name3 As DataType3  

Note: The statements given below are also used to declare the variable with their data type:

1. Const num As Integer = 10  
2. Static name As String  
3. Public Const name As String = "JavaTpoint"  
4. Private Const PI As Double = 3.14  

Example of Const keyword

Const1.vb

1. Module Const1  
2.     Sub main()  
3.         'declaration and initialization of Constant variable using Const keywords  
4.         Const intData As Integer = 20  
5.         Const name As String = "JavaTpoint"  
6.         Const topic As String = "VB.NET"  
7.         Const PI = 3.14  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

8.         Dim radius, area As Integer  
9.   
10.         Console.WriteLine(" Constant integer is {0}", intData)  
11.         Console.WriteLine(" You have entered {0}", name)  
12.         Console.WriteLine(" Your Topic is {0}", topic)  
13.         Console.WriteLine("Enter the Radius")  
14.         radius = Console.ReadLine()  
15.         area = PI * radius * radius  
16.         Console.WriteLine(" Area of Circle is {0}", area)  
17.         Console.ReadKey()  
18.   
19.     End Sub  
20. End Module  

Output:

Constant integer is 20
You have entered JavaTpoint
Your Topic is VB.NET
Enter the Radius
7
Area of Circle is 154

Scope of Variable in VB.NET


The scope of a variable determines the accessible range of a defined variable at the time of declaration in
any block, module, and class. You can access it if the variable is in a particular region or scope in the same
block. And if the variable goes beyond the region, its scope expires.

The following are the methods to represent the scope of a variable in VB.NET.

1. Procedure Scope
2. Module Scope
3. Public Scope

Procedure (local) scope


A local variable is a type of variable defined within a procedure scope, block, or function. It is available
with a code inside the procedure, and it can be declared using the Dim or static statement. These
variables are not accessible from outside of the local method. However, the local variable can be easily
accessed by the nested programming function in the same method.

1. Dim X As Integer  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Local variables exist until the procedure in which they are declared is executed. Once a procedure is
executed, the values of its local variables will be lost, and the resources used by these variables will be
released. And when the block is executed again, all the local variables are rearranged.

Let's create a program that displays the local scope of a variable within a function.

Local_Scope.vb

1. Imports System  
2. Module Local_scope  
3.     Sub Main()  
4.         Console.WriteLine(" Scope of local varibale within a function")  
5.         local() ' call local() and local() function without any object reference  
6.         local2()  
7.         Console.WriteLine("press any key to exit...")  
8.         Console.ReadKey()  
9.     End Sub  
10.     Sub local()  
11.         Dim X As Integer  
12.         ' declaration of local variable  
13.         X = 50  
14.         Console.WriteLine(" Value of Local value X is {0}", X)  
15.   
16.     End Sub  
17.     Sub local2()  
18.         Dim X As String  
19.         ' scope of local variable within a function  
20.         X = "JavaTpoint"  
21.         Console.WriteLine(" Value of X is {0}", X)  
22.     End Sub  
23. End Module  

Output:

Scope of local variable within a function


Value of Local value X is 50
Value of X is JavaTpoint
press any key to exit...

Module Scope
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
All existing procedures can easily identify a variable that is declared inside a module sheet is called
a module-level variable. The defined module variable is visible to all procedures within that module
only, but it is not available for other module's procedures. The Dim or private statement at the top of the
first procedure declaration can be declared the module-level variables. It means that these variables cannot
be declared inside any procedure block. Further, these variables are useful to share information between
the procedures in the same module. And one more thing about the module-level variable is that these
variables can remains existence as long as the module is executed.

' It is the declaration section of the module

1. Private num As Integer ' A private module-level variable  
2. Dim name As String ' Another private module-level variable   

Let's create a program that display the module level variable in VB.NET.

Module_scope.vb

1. Imports System  
2. Module Module_scope  
3. 'module-level variable declaration  
4.     Dim x As Integer   
5.     Private y As Integer  
6.     Private name As String = "JavaTpoint"  
7.     Sub example()  
8.         x = 10  
9.         y = x + 10  
10.         Console.WriteLine(" Value of Y is {0}", y)  
11.     End Sub  
12.     Sub example2()  
13.         Console.WriteLine(" Value of X is {0}", x)  
14.         Console.WriteLine(" Value of Y is {0}", y)  
15.         Console.WriteLine(" Name is {0}", name)  
16.     End Sub  
17.     Sub example3()  
18.         Dim A As Integer  ' local variable or local scope  
19.         A = x + y  
20.         Console.WriteLine(" Local scope within a function of variable A {0}", A)  
21.     End Sub  
22.     Sub Main()  
23.         Console.WriteLine(" Module scope of variable")  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

24.         example()  
25.         example2()  
26.         example3()  
27.         Console.WriteLine("Press any key to exit...")  
28.         Console.ReadKey()  
29.     End Sub  
30. End Module  

Output:

Module scope of variable


Value of Y is 20
Value of X is 10
Value of Y is 20
Name is JavaTpoint
Local scope within a function of variable A 30
Press any key to exit...

Global (Public) Scope


As the name defines, a global variable is a variable that is used to access the variables  globally in a
program. It means these variables can be accessed by all the procedures or modules available in a
program. To access the variables globally in a program, you need to use the friend or public
keyword with a variable in a module or class at the top of the first procedure function. Global scope is also
known as the Namespace scope.

Let's create a program that uses the global variable.

Global_scope1.vb

1. Imports System      
2. Module Global_scope1  
3.     'Global declaration of a variable  
4.     Public str As String = "Hello, Programmer."  
5.     Public topic As String  
6.     Public exp As Integer  
7.   
8.     Sub Main()  
9.         Console.WriteLine(" You have passed {0}", str)  
10.         Console.WriteLine(" Enter the topic name")  
11.         topic = Console.ReadLine  
12.         Console.WriteLine(" Topic Name :{0}", topic)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

13.         Console.WriteLine("How many years of experienced in {0}?", topic)  
14.         exp = Console.ReadLine  
15.         Console.WriteLine(" Your Experienced is {0} ", exp)  
16.         Console.ReadKey()  
17.     End Sub  
18.   
19. End Module  

Output:

You have passed Hello, Programmer


Enter the topic name
VB.NET
Topic Name :VB.NET
How many years of experienced in VB.NET?
10
Your Experienced is 10

VB.NET Operators
In VB.NET programming, the Operator is a symbol that is used to perform various operations on
variables. VB.NET has different types of Operators that help in performing logical and mathematical
operations on data values. The Operator precedence is used to determine the execution order of different
Operators in the VB.NET programming language.

What is VB.NET Operator?


In VB.NET, operator is a special symbol that tells the compiler to perform the specific logical or
mathematical operation on the data values. The data value itself (which can be either a variable or a
constant) is called an operand, and the Operator performs various operations on the operand.

For example: In the expression,

3+2-1

The symbol + and - are the Operators, and the 3, 2, and 1 are operands.

Different Types of VB.NET Operators

Following are the different types of Operators available in VB.NET:

o Arithmetic Operators
o Comparison Operators
o Logical and Bitwise Operators
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

o Bit Shift Operators


o Assignment Operators
o Concatenation Operators
o Miscellaneous Operators

Arithmetic Operators
The Arithmetic Operators in VB.NET, used to perform mathematical operations such as subtraction,
addition, multiplication, division, etc. on the operands in VB.NET. These are as follows:

Arithmetic Operators in VB.NET

Operator Description Example


s

^ It is an exponentiation Operator that is used to raises one operand to Y ^ X (X to the


the power of another operand. power Y)

+ The addition Operator is used to add numeric data, as well as X+Y


concatenate two string variables.

- It is a subtraction Operator, which is used to subtract the second X-Y


operand from the first operand.

* The multiplication Operator is used to multiply the operands X*Y

/ It is a division Operator used to divide one operand by another X/Y


operand and returns a floating-point result.

\ It is an integer division Operator, which is similar to division Operator, X\Y


except that it returns an integer result while dividing one operand to
another operand.

Mod It is a modulo (Modulus) Operator, which is used to divide two X Mod Y


operands and returns only a remainder.

Example of Arithmetic Operators in VB.NET:

Arithmetic_Operator.vb

1. Imports System  
2. Module Arithmetic_Operator  
3.     Sub Main()  
4.         'Declare a, b And c as integer Data Type()  
5.         Dim a, b, c As Integer  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

6.         Dim d As Single  
7.         a = 17  
8.         b = 4  
9.         ' Use of + Operator  
10.         c = a + b  
11.         Console.WriteLine(" Sum of a + b is {0}", c)  
12.   
13.         'Use of - Operator  
14.         c = a - b  
15.         Console.WriteLine(" Subtraction of a - b is {0}", c)  
16.   
17.         'Use of * Operator  
18.         c = a * b  
19.         Console.WriteLine(" Multiplication of a * b is {0}", c)  
20.   
21.         'Use of / Operator  
22.         d = a / b  
23.         Console.WriteLine(" Division of a / b is {0}", d)  
24.   
25.         'Use of \ Operator  
26.         c = a \ b  
27.         Console.WriteLine(" Similar to division Operator (return only integer value) of a - b is {0}", c)  
28.   
29.         'Use of Mod Operator  
30.         c = a Mod b  
31.         Console.WriteLine(" Modulus of a Mod b is {0}", c)  
32.   
33.         'Use of ^ Operator  
34.         c = a ^ b  
35.         Console.WriteLine(" Power of a ^ b is {0}", c)  
36.         Console.WriteLine("Press any key to exit...")  
37.         Console.ReadKey()  
38.     End Sub  
39. End Module  

Now compile and execute the above program, by pressing the F5 button or Start button from the Visual
Studio; then it shows the following result:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Comparison Operators
As the name suggests, the Comparison Operator is used to compare the value of two variables or
operands for the various condition such as greater, less than or equal, etc. and returns a Boolean value
either true or false based on the condition.

Operato Description Example


r

= It checks whether the value of the two operands is equal; If (A = B)


yes, it returns a true value, otherwise it shows False.

<> It is a Non-Equality Operator that checks whether the value (A <> B), check Non-
of the two operands is not equal; it returns true; otherwise, it Equality
shows false.

> A greater than symbol or Operator is used to determine (A > B); if yes, TRUE,
whether the value of the left operand is greater than the
value of the right operand; If the condition is true, it returns Else FALSE
TRUE; otherwise, it shows FALSE value.

< It is a less than symbol which checks whether the value of (A < B); if the condition is
the left operand is less than the value of the right operand; If true, returns TRUE else
the condition is true, it returns TRUE; otherwise, it shows FALSE
FALSE value.

>= It is greater than equal to which checks two conditions A >= B


whether the first operand is greater than or equal to the
second operand; if yes, it returns TRUE; otherwise, it shows
False.

<= This symbol represents less than equal to which determines A <= B
the first operand is less than or equal to the second operand,
and if the condition is true, it returns TRUE; otherwise, it
shows FALSE.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Is The Is Operator is used to validate whether the two objects result = obj1 Is obj2
reference the same variable or object; If the test is true, it
returns True; otherwise, the result is False. In short, it checks
the equality of the objects. An Is Operator is also used to
determine whether the object refers to a valid object.

IsNot The IsNot Operator is similar to Is Operator, except that the Result = obj1 IsNot obj2
two object references the different object; if yes, the result is
True; otherwise, the result is False.

Like The Like Operator is used to check the pattern expression of result = string Like the
string variable; And if the pattern matched, the result is True; pattern, the pattern
otherwise, it returns False. represents the series of
characters used by Like
Operator.

Example of Comparison Operators in VB.NET

Comparison_Operator.vb

1. Imports System  
2. Module Comparison_Operator  
3.     Sub Main()  
4.         'declaration of Integer, Object and String Data Type variables  
5.         Dim x As Integer = 5  
6.         Dim y As Integer = 10  
7.         Dim Result, obj, obj2 As Object  
8.         Dim str, str2 As String  
9.         str = "Apple12345"  
10.         str2 = "Apple12345"  
11.         obj = 10  
12.         obj2 = 20  
13.   
14.         Console.WriteLine(" Program of Comparison Operator")  
15.         'Use of > Operator  
16.         Console.WriteLine(" Output of x > y is {0}", x > y)  
17.   
18.         'Use of < Operator  
19.         Console.WriteLine(" Output of x < y is {0}", x < y)  
20.   
21.         'Use of = Operator  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

22.         Console.WriteLine(" Output of x = y is {0}", x = y)  
23.   
24.         'Use of <> Operator  
25.         Console.WriteLine(" Output of x <> y is {0}", x <> y)  
26.   
27.         'Use of >= Operator  
28.         Console.WriteLine(" Output of x >= y is {0}", x >= y)  
29.   
30.         'Use of <= Operator  
31.         Console.WriteLine(" Output of x <= y is {0}", x <= y)  
32.   
33.         'Use of Is Operator  
34.         Result = obj Is obj2  
35.         Console.WriteLine(" Output of obj Is obj2 is {0}", Result)  
36.   
37.         'Use of Is Operator  
38.         Result = obj IsNot obj2  
39.         Console.WriteLine(" Output of obj IsNot obj2 is {0}", Result)  
40.   
41.         'Use of Like Operator  
42.         Result = str Like str2  
43.         Console.WriteLine(" Output of str Like str2 is {0}", Result)  
44.   
45.         Console.WriteLine(" Press any key to exit...")  
46.         Console.ReadKey()  
47.     End Sub  
48. End Module  

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it
returns the following output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Logical and Bitwise Operators


The logical and bitwise Operators work with Boolean (true or false) conditions, and if the conditions
become true, it returns a Boolean value. The following are the logical and bitwise Operators used to
perform the various logical operations such as And, Or, Not, etc. on the operands (variables). Suppose
there are two operand A and B, where A is True, and B is False.

Operato Description Example


r

And The And Operator represents, whether both the operands are true; the (A And B),
result is True. result = False

Or It is an Or Operator that returns a true value; if anyone operand is true (A Or B), result
from both the operands. = True

Not The Not Operator is used to reverse the logical condition. For example, Not A
if the operand's logic is True, it reveres the condition and makes it
False. Or

Not(A And B) is
True

Xor It is an Exclusive OR Operator that represents, whether both the A Xor B is True
expression is true or false, the result is True; otherwise, the result is
False.

AndAlso It is a logical AND Operator that performs short-circuit operation on A AndAlso B =


the variables, and if both the operands are true, the result is True else False
the result is False.

OrElse It is a logical OR Operator that perform short-circuit operation on A OrElse B =


Boolean data. If anyone of the operand is true, the result is True else True
the result is False.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

IsFalse The IsFalse Operator is used to determine whether an expression is


False.

IsTrue The IsTrue Operator is used to determine whether an expression is


True.

Example of Logical and Bitwise Operator:

Logic_Bitwise.vb

1. Imports System  
2. Module Logic_Bitwise  
3.     Sub Main()  
4.         Dim A As Boolean = True  
5.         Dim B As Boolean = False  
6.         Dim c, d As Integer  
7.         c = 10  
8.         d = 20  
9.   
10.         'Use of And Operator  
11.         If A And B Then  
12.             Console.WriteLine(" Operands A And B are True")  
13.         End If  
14.   
15.         'Use of Or Operator  
16.         If A Or B Then  
17.             Console.WriteLine(" Operands A Or B are True")  
18.         End If  
19.   
20.         'Use of Xor Operator  
21.         If A Xor B Then  
22.             Console.WriteLine(" Operands A Xor B is True")  
23.         End If  
24.   
25.         'Use of And Operator  
26.         If c And d Then  
27.             Console.WriteLine(" Operands c And d is True")  
28.         End If  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

29.   
30.         'Use of Or Operator  
31.         If c Or d Then  
32.             Console.WriteLine(" Operands c Or d is True")  
33.         End If  
34.   
35.         'Use of AndAlso Operator  
36.         If A AndAlso B Then  
37.             Console.WriteLine(" Operand A AndAlso B is True")  
38.         End If  
39.   
40.         'Use of OrElse Operator  
41.         If A OrElse B Then  
42.             Console.WriteLine(" Operand A OrElse B is True")  
43.         End If  
44.   
45.         'Use of Not Operator  
46.         If Not (A And B) Then  
47.             Console.WriteLine(" Output of Not (A And B) is True")  
48.         End If  
49.   
50.         Console.WriteLine (" Press any key to exit?")  
51.         Console.ReadKey()  
52.     End Sub  
53. End Module  

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it
returns the following output:

Bit Shift Operators


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
The Bit Shit Operators are used to perform the bit shift operations on binary values either to the right or to
the left.

Bit Shift operations in VB.NET

Operato Description
r

AND The Binary AND Operator are used to copy the common binary bit in the result if the bit
exists in both operands.

OR The Binary OR Operator is used to copy a common binary bit in the result if the bit found
in either operand.

XOR The Binary XOR Operator in VB.NET, used to determine whether a bit is available to copy
in one operand instead of both.

Not The binary NOT Operator is also known as the binary Ones' Compliment Operator, which
is used to flip binary bits. This means it converts the bits from 0 to 1 or 1 to 0 binary bits.

<< The Binary Left Shift Operator is used to shift the bit to the left side.

>> The Binary Right Shift Operator is used to shift the bit to the right side.

Example of Bit Shift Operator in VB.NET:

BitShift_Operator.vb

1. Imports System  
2. Module Bitshift_Operator  
3.     Sub Main()  
4.         Dim x, y, z As Integer  
5.         x = 12  
6.         y = 25  
7.         Dim a, b As Double  
8.         a = 5 ' a = 5(00000101)  
9.         b = 9 ' b = 9(00001001)  
10.   
11.         ' Use of And Operator  
12.         z = x And y  
13.         Console.WriteLine(" BitShift Operator x And y is {0}", z)  
14.   
15.         'Use of Or Operator  
16.         z = x Or y  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

17.         Console.WriteLine(" BitShift Operator x Or y is {0}", z)  
18.   
19.         z = x Xor y  
20.         Console.WriteLine(" BitShift Operator x Xor y is {0}", z)  
21.   
22.         z = Not y  
23.         Console.WriteLine(" BitShift Operator Not y is {0}", z)  
24.   
25.         'Use of << Left-Shift Operator  
26.         ' Output is 00001010  
27.         Console.WriteLine(" Bitwise Left Shift Operator - a<<1 = {0}", a << 1)  
28.   
29.         'Output is 00010010  
30.         Console.WriteLine(" Bitwise Left Shift Operator - b<<1 = {0}", b << 1)  
31.   
32.         'Use of >> Right-Shift Operator  
33.         'Output is 00000010  
34.         Console.WriteLine(" Bitwise Right Shift Operator - a>>1 = {0}", a << 1)  
35.   
36.         'Output is 00000100  
37.         Console.WriteLine(" Bitwise Right Shift Operator - b>>1 = {0}", a << 1)  
38.   
39.         Console.WriteLine(" Press any key to exit...")  
40.         Console.ReadKey()  
41.     End Sub  
42. End Module  

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it
returns the following output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Assignment Operators
The Assignment Operators are used to assign the value to variables in VB.NET.

Assignment Operators in VB.NET

Operato Description Example


r

= It is a simple assignment Operator used to assign a right- X = 5, X assign a value 5


side operand or value to a left side operand. X = P + Q, (P + Q) variables
or value assign to X.

+= An Add AND assignment Operator is used to add the value X += 5, which means
of the right operand to the left operand. And the result is X= X+5 ( 5 will add and
assigned to the left operand. assign to X and then result
saved to Left X operand)

-= It is a Subtract AND assignment Operator, which subtracts X -= P, which is same as X


the right operand or value from the left operand. And then, =X-P
the result will be assigned to the left operand.

*= It is a Multiply AND assignment Operator, which multiplies X *= P, which is same as X


the right operand or value with the left operand. And then, =X-P
the result will be assigned to the left operand.

/= It is a Divide AND assignment Operator, which divides the X /= P, which is same as X


left operand or value with the right operand. And then, the =X-P
result will be assigned to the left operand (in floating-
point).

\= It is a Divide AND assignment Operator, which divides the X \= P, which is same as X


left operand or value with the right operand. And then, the =X-P
result will be assigned to the left operand (in integer-point
division).

^= It is an expression AND assignment Operator, which raises X ^= P, which is same as X


the left operand or value to the right operand's power. And =X^P
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

then, the result will be assigned to the left operand.

&= It is a concatenate string assignment Operator used to bind Str &= name, which is same
the right-hand string or variable with the left-hand string or as Str = Str & name
variable. And then, the result will be assigned to the left
operand.

Example of Assignment Operator in VB.NET:

Assign_Operator.vb

1. Imports System  
2. Module Assign_Operator  
3.     Sub Main()  
4.         'Declare variable and b As Integer  
5.         Dim A As Integer = 5  
6.         Dim B As Integer  
7.         Dim Str, name As String  
8.         name = "come"  
9.         Str = "Wel"  
10.   
11.         'Use of = Operator  
12.         B = A  
13.         Console.WriteLine(" Assign value A to B is {0}", B)  
14.   
15.         'Use of += Operator  
16.         B += A  
17.         Console.WriteLine(" Output of B += A is {0}", B)  
18.   
19.         'Use of -= Operator  
20.         B -= A  
21.         Console.WriteLine(" Output of B -= A is {0}", B)  
22.   
23.         'Use of *= Operator  
24.         B *= A  
25.         Console.WriteLine(" Output of B *= A is {0}", B)  
26.   
27.         'Use of /= Operator  
28.         B /= A  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

29.         Console.WriteLine(" Output of B /= A is {0}", B)  
30.   
31.         'Use of = Operator  
32.         B \= A  
33.         Console.WriteLine(" Output of B \= A is {0}", B)  
34.   
35.         'Use of ^= Operator  
36.         B ^= A  
37.         Console.WriteLine(" Output of B ^= A is {0}", B)  
38.   
39.         'Use of &= Operator  
40.         Str &= name  
41.         Console.WriteLine(" Output of Str &= name is {0}", Str)  
42.   
43.         Console.WriteLine (" Press any key to exit...")  
44.         Console.ReadKey()  
45.     End Sub  
46. End Module  

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it
returns the following output:

Concatenation Operators
In VB.NET, there are two concatenation Operators to bind the operands:

Operato Description Example


r
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

& It is an ampersand symbol that is used to bind two or more operand Result = Wel
together. Furthermore, a nonstring operand can also be concatenated & come,
with a string variable (but in that case, Option Strict is on). Result =
Welcome

+ It is also used to add or concatenate two number or string. Result = Wel


+ come,
Result =
Welcome

Example of Concatenation Operators in VB.NET.

MyProgram.vb

1. Imports System  
2. Module MyProgram  
3.     Sub Main()  
4.         Dim str As String = "Wel"  
5.         Dim str2 As String = "come"  
6.         Dim str3 As String = " "  
7.         Dim str4 As String = "to JavatPoint"  
8.         Dim result As String  
9.         Dim result2 As String  
10.         result = str & str2  
11.         Console.WriteLine(" Result = str & str2 gives = {0}", result)  
12.         result2 = str + str2 + str3 + str4  
13.         Console.WriteLine(" Result = str + str2 + str3 +str4 gives = {0}", result2.ToString)  
14.   Console.ReadLine()  
15.     End Sub  
16. End Module  

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it
returns the following output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Miscellaneous Operators

There are some important Operator in VB.NET

Operator Description Example

Await An Await Operator is used in an operand Dim output as out = Await


to suspend the execution of an AsyncMethodThatReturnsResult() Await
asynchronous method or lambda AsyncMethod()
expression until the awaited task
completes.

AddressOf The AddressOf Operator is used to AddHandler Button2.Click, AddressOf


provide a reference to the address of a Button2_Click
procedure.

GetType A GetType Operator is used to retrieve the MsgBox(GetType(String).ToString())


type of the specified object. In addition,
the retrieved object type provides various
information such as methods, properties,
and events.

Function It defines the lambda expression, which Dim mul2 = Function(num As Integer) num
Expression declares the parameter and code. A *4
Lambda expression is a function that is Console.WriteLine(mul2(4))
used to calculate and return value without
defining the name.

If The If Operator using short circuit Dim a = -4


evaluation to conditionally return a single Console.WriteLine(If (a >= 0,
object value from two defined object "Positive", "Negative"))
values. The If Operator can be used with
two or three defined arguments.

Example of Miscellaneous Operators in VB.NET.

Misc_Operator.vb

1. Imports System  
2. Module Misc_Operator  
3.     Sub Main()  
4.         ' Initialize a variable  
5.         Dim a As Integer = 50  
6.         ' GetType of the Defined Type  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

7.         Console.WriteLine(GetType(Double).ToString())  
8.         Console.WriteLine(GetType(Integer).ToString())  
9.         Console.WriteLine(GetType(String).ToString())  
10.         Console.WriteLine(GetType(Single).ToString())  
11.         Console.WriteLine(GetType(Decimal).ToString())  
12.   
13.         'Use of Function()   
14.         Dim multiplywith10 = Function(sum As Integer) sum * 10  
15.         Console.WriteLine(multiplywith10(10))  
16.         Console.WriteLine(If(a >= 0, "Negative", "Positive"))  
17.   
18.         Console.WriteLine (" Press any key to exit...")  
19.         Console.ReadLine()  
20.   
21.     End Sub  
22. End Module  

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it
returns the following output:

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
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

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

Negation Not

Conjunction And, AndAlso

Inclusive disjunction Or, Else

Exclusive disjunction Xor Lowest

Example of Operator Precedence in VB.NET.

Operator_Precedence.vb

1. Imports System  
2. Module Operator_Precedence  
3.     Sub Main()  
4.         'Declare and Initialize p, q, r, s variables  
5.         Dim p As Integer = 30  
6.         Dim q As Integer = 15  
7.         Dim r As Integer = 10  
8.         Dim s As Integer = 5  
9.         Dim result As Integer  
10.   
11.         Console.WriteLine("Check Operator Precedence in VB.NET")  
12.         'Check Operator Precedence  
13.         result = (p + q) * r / s      '  45 * 10 / 5  
14.         Console.WriteLine("Output of (p + q) * r / s is : {0}", result)  
15.   
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

16.         result = (p + q) * (r / s)   ' (45) * (10/5)  
17.         Console.WriteLine("Output of (p + q) * (r / s) is  : {0}", result)  
18.   
19.         result = ((p + q) * r) / s    ' (45 * 10 ) / 5  
20.         Console.WriteLine("Output of ((p + q) * r) / s is  : {0}", result)  
21.   
22.         result = p + (q * r) / s     '  30 + (150/5)  
23.         Console.WriteLine("Output of p + (q * r) / s is  : {0}", result)  
24.   
25.         result = ((p + q * r) / s)     '  ((30 + 150) /5)  
26.         Console.WriteLine("Output of ((p + q * r) / s) is  : {0}", result)  
27.   
28.         Console.WriteLine(" Press any key to exit...")  
29.         Console.ReadKey()  
30.     End Sub  
31. End Module  

Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it
returns the following output:

VB.NET Control Statements


In VB.NET, the control statements are the statements that controls the execution of the program on the
basis of the specified condition. It is useful for determining whether a condition is true or not. If the
condition is true, a single or block of statement is executed. In the control statement, we will use  if- Then,
if Then Else, if Then ElseIf and the Select case statement.

We can define more than one condition to be evaluated by the program with statements. If the defined
condition is true, the statement or block executes according to the condition, and if the condition is false,
another statement is executed.

The following figure shows a common format of the decision control statements to validate and execute a
statement:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

The above diagram shows that if the defined condition is true, statement_1 will be executed, and if the
condition is false, statement_2 will be executed.

VB.NET provides the following conditional or decision-making statements.

o If-Then Statement
o If-Then Else Statement
o If-Then ElseIf Statement
o Select Case Statement
o Nested Select Case Statements

If-Then Statement
The If-Then Statement is a control statement that defines one or more conditions, and if the particular
condition is satisfied, it executes a piece of information or statements.

Syntax:

1. If condition Then  
2. [Statement or block of Statement]  
3. End If  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
In If-Then Statement, the condition can be a Boolean, logical, or relational condition, and the statement
can be single or group of statements that will be executed when the condition is true.

Example 1: Write a simple program to print a statement in VB.NET.

Module1.vb

1. Module Module1  
2.     ' Declaration of variable str  
3.     Dim str As String = "JavaTpoint"  
4.     Sub Main()  
5.         ' if str equal to "JavaTpoint", below Statement will be executed.  
6.         If str = "JavaTpoint" Then  
7.             Console.WriteLine("Welcome to the JavaTpoint")  
8.         End If  
9.     Console.WritLine("press any key to exit?")  
10.     Console.ReadKey()  
11.     End Sub  
12. End Module  

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

As we can see in the above example, if the value of str is equal to JavaTpoint, the condition is true, and it
prints the Statement.

Example 2: Write a program to print a number is greater than another number in VB.NET.

if_statment2.vb

1. Module if_statement2  
2.     Sub Main()  
3.         ?Definition of variables  
4.         Dim no1, no2 As Integer  
5.         Console.WriteLine("Enter any two number:")  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

6.         no1 = Console.ReadLine() ?read no1 from user  
7.         no2 = Console.ReadLine() ?read no2 from user  
8.         If no1 > no2 Then  
9.             Console.WriteLine("First number is greater than second number")  
10.         End If  
11.         If no1 < no2 Then  
12.             Console.WriteLine("Second number is greater than First number")  
13.         End If  
14.         Console.WriteLine("press any key to exit...")  
15.         Console.ReadKey()   
16. End Sub  
17. End Module  

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

In the above program, we enter two numbers to find the greater number using the relational operator. And
if the first number is greater than the other, the first statement is executed; otherwise, the second
statement will be executed.

If-Then-Else Statement
The If-Then Statement can execute single or multiple statements when the condition is true, but when the
expression evaluates to false, it does nothing. So, here comes the If-Then-Else Statement. The IF-Then-
Else Statement is telling what If condition to do when if the statement is false, it executes the Else
statement. Following is the If-Then-Else statement syntax in VB.NET as follows:

Syntax:

1. If (Boolean_expression) Then  
2. 'This statement will execute if the Boolean condition is true  
3. Else  
4. 'Optional statement will execute if the Boolean condition is false  
5. End If  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Flow chart

The above diagram represents that if the Boolean expression (condition) is true, the if statement will
execute, and if the Boolean expression is false, Else code or statement will be executed. After that, the
control transfer to the next statement, which is immediately after the If-Then-Else control statement.

Example 1: Write a program to check whether the number is even or odd.

If_Else_statment.vb

1. Module If_Else_statement  
2.     Sub Main()  
3.         Dim num As Integer  
4.         Console.WriteLine("Enter the Number")  
5.         num = Console.ReadLine() 'read data from console  
6.   
7.         If (num Mod 2 = 0) Then ' if condition is true, print the if statement  
8.             Console.WriteLine("It is an even number")  
9.   
10.         Else 'otherwise, Else statement is executed.  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

11.             Console.WriteLine("It is an odd number")  
12.         End If  
13.   
14.     Console.WriteLine("press any key to exit...")  
15.         Console.ReadKey()  
16.     End Sub  
17. End Module  

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

Example 2: Write a program to print the larger and smaller of the two numbers.

if_else_statment2.vb

1. Module if_else_statement2  
2.     Sub Main()  
3.         Dim a As Integer  
4.         Dim b As Integer  
5.         Console.WriteLine("Enter the first number : ")  
6.         a = Console.ReadLine()  
7.   
8.         Console.WriteLine("Enter the second number : ")  
9.         b = Console.ReadLine()  
10.   
11.         If a > b Then  
12.             Console.WriteLine(" larger number = {0} and smaller number = {1} ", a, b)  
13.         Else  
14.             Console.WriteLine(" larger number = {0} and smaller number = {1} ", b, a)  
15.         End If  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

16.   
17.         Console.WriteLine("press any key to exit...")  
18.         Console.ReadKey()  
19.     End Sub  
20. End Module  

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

VB.NET If-Then-ElseIf statement


The If-Then-ElseIf Statement provides a choice to execute only one condition or statement from multiple
statements. Execution starts from the top to bottom, and it checked for each If condition. And if the
condition is met, the block of If the statement is executed. And if none of the conditions are true, the
last block is executed. Following is the syntax of If-Then-ElseIf Statement in VB.NET as follows:

Syntax

1. If(condition 1)Then  
2.    ' Executes when condition 1 is true   
3. ElseIf( condition 2)Then  
4.    ' Executes when condition 2 is true   
5. ElseIf( boolean_expression 3)Then  
6.    ' Executes when the condition 3 is true   
7. Else   
8.    ' executes the default statement when none of the above conditions is true.   
9. End If  

Flowchart

The following diagram represents the functioning of the If-Else-If Statement in the VB.NET programming
language.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

If this condition is true in the flowchart of the if-else-if statement, the statement is executed within the if
block. If the condition is not true, it passes control to the next ElseIf condition to check whether the
condition is matched. And if none of the conditions are matched, the else block is executed.

Example 1: Write a program to show the uses of If... ElseIf statements.

if_elseIf.vb

1. Module if_elseIf  
2.     Sub Main()  
3.         Dim var1 As Integer  
4.   
5.         Console.WriteLine(" Input the value of var1: ")  
6.         var1 = Console.ReadLine()  
7.         If var1 = 20 Then  
8.             'if condition is true then print the following statement'  
9.             Console.WriteLine(" Entered value is equal to 20")  
10.         ElseIf var1 < 50 Then  
11.             Console.WriteLine(" Entered value is less than 50")  
12.           
13.          ElseIf var1 >= 100 Then  
14.             Console.WriteLine(" Entered value is greater than 100")  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

15.         Else  
16.             'if none of the above condition is satisfied, print the following statement  
17.             Console.WriteLine(" Value is not matched with above condition")  
18.         End If  
19.         Console.WriteLine(" You have entered : {0}", var1)  
20.         Console.WriteLine(" press any key to exit...")  
21.         Console.ReadKey()  
22.     End Sub  
23. End Module  

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

Example 2: Write a program to use the If-Then-ElseIf Statement for calculating the division obtained by
the student. Also, take the marks obtained by the student in 5 different subjects from the keyboard.

if_elseIf2.vb

1. Module If_elseIf2    
2.     Sub Main()      ' execution start from Main() method  
3.         Dim m1, m2, m3, m4, m5, per As Integer  
4.         Console.WriteLine("Enter marks in five subjects ")  
5.         ' Read the marks of five subject  
6.         m1 = Console.ReadLine()  
7.         m2 = Console.ReadLine()  
8.         m3 = Console.ReadLine()  
9.         m4 = Console.ReadLine()  
10.         m5 = Console.ReadLine()  
11.         per = (m1 + m2 + m3 + m4 + m5) / 5  
12.         If (per >= 70) Then  
13.             'if condition is true, print the first division  
14.             Console.WriteLine(" First division")  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

15.         ElseIf (per >= 60) Then  
16.             'if ElseIf condition is true, print the second division  
17.             Console.WriteLine(" Second division")  
18.         ElseIf (per >= 50) Then  
19.             'if ElseIf condition is true, print the third division  
20.             Console.WriteLine(" Third division")  
21.         ElseIf (per >= 40) Then  
22.             'if ElseIf condition is true, print only pass with grace   
23.             Console.WriteLine(" Only Pass with Grace")  
24.         Else  
25.             'if none of the condition is true, print the Failed  
26.             Console.WriteLine(" Failed")  
27.         End If  
28.         Console.WriteLine("press any key to exit...")  
29.         Console.ReadKey()  
30.     End Sub  
31.   
32. End Module  

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

Select Case Statement


In VB.NET, the Select Case statement is a collection of multiple case statements, which allows executing a
single case statement from the list of statements. A selected case statement uses a variable to test for
equality against multiple cases or statements in a program. If the variable is matched with any test cases,
that statement will be executed. And if the condition is not matched with any cases, it executes the default
statement.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Using the select case statement in VB.NET programming, you can replace the uses of multiple If-Then-Else
If statement from the program for better readability and easy to use.

Syntax

Following is the syntax of the Select Case statement in VB.NET, as follows:

1. Select Case [variable or expression]  
2. Case value1 'defines the item or value that you want to match.  
3. // Define a statement to execute  
4.   
5. Case value2 'defines the item or value that you want to match.  
6. // Define a statement to execute  
7.   
8. Case Else  
9. // Define the default statement if none of the conditions is true.  
10. End Select   

Furthermore, you can also set more than one condition in a single case statement, such as:

1. Select Case Variable / expression  
2. Case value1  
3. Statement1  
4.   
5. Case value2, value3  
6. Statement2  
7.   
8. Case Else  
9. // define the default statement if none of the condition is true  
10. End Select   

Flowchart of Select Case Statement

The following flowchart represents the functioning of the Select case statement in the VB.NET
programming language.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

In Flowchart, the Select Case statement represents the evaluating of the process start from top to bottom.
If the expression or value is matched with the first select case, statement -1 is executed else the control
transfer to the next case for checking whether the expression is matching or not. Similarly, it checks all
Select case statements for evaluating. If none of the cases are matched, the Else block statement will be
executed, and finally, the Select Case Statement will come to an end.

Example 1: Write a program to display the Days name using the select case statement in VB.NET.

Select_case.vb

1. Imports System  
2. Module Select_case  
3.     Sub Main()  
4.         'define a local variable.   
5.         Dim Days As String  
6.         Days = "Thurs"  
7.         Select Case Days  
8.             Case "Mon"  
9.                 Console.WriteLine(" Today is Monday")  
10.             Case "Tue"  
11.                 Console.WriteLine(" Today is Tuesday")  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

12.             Case "Wed"  
13.                 Console.WriteLine("Today is Wednesday")  
14.             Case "Thurs"  
15.                 Console.WriteLine("Today is Thursday")  
16.             Case "Fri"  
17.                 Console.WriteLine("Today is Friday")  
18.             Case "Sat"  
19.                 Console.WriteLine("Today is Saturday")  
20.             Case "Sun"  
21.                 Console.WriteLine("Today is Sunday")  
22.             Case Else  
23.                 Console.WriteLine(" You have typed Something wrong")  
24.   
25.         End Select  
26.         Console.WriteLine("You have selected : {0}", Days)  
27.         Console.WriteLine("Press any key to exit...")  
28.         Console.ReadLine()  
29.     End Sub  
30. End Module  

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

In the select case statement, the value of Days "Thurs" will compare all the available select cases' values in
a program. If a value matched with any condition, it prints the particular statement, and if the value is not
matched with any select case statement, it prints the default message.

Example 2: Write a program to perform an arithmetic operation using the Select case statement in
VB.NET.

Operation.vb

1. Imports System  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

2. Module Operation  
3.     Sub main()  
4.         'declaration of the variables  
5.         Dim num1, num2, sum As Integer  
6.         Dim def As Char  
7.         'initialization of num1 and num2 variable  
8.         num1 = 2  
9.         num2 = 6  
10.         Console.WriteLine(" Want to perform any operation?")  
11.         Console.WriteLine(" A for Addition")  
12.         Console.WriteLine(" S for Subtraction")  
13.         Console.WriteLine(" M for Multiplication")  
14.         Console.WriteLine(" D for Division")  
15.         Console.WriteLine(" Please enter any input")  
16.         def = Console.ReadLine()  
17.         Select Case def  
18.             Case "A"  
19.                 'perform Addition  
20.                 sum = num1 + num2  
21.                 Console.WriteLine(" Addition of two number is :{0}", sum)  
22.             Case "S"  
23.                 'perform Subtraction  
24.                 sum = num2 - num1  
25.                 Console.WriteLine(" Subtraction of two number is :{0}", sum)  
26.             Case "M"  
27.                 'perform Multiplication  
28.                 sum = num1 * num2  
29.                 Console.WriteLine(" Multiplication of two number is :{0}", sum)  
30.             Case "D"  
31.                 'Peform Division  
32.                 sum = num2 / num1  
33.                 Console.WriteLine(" Division of two number is :{0}", sum)  
34.             Case Else  
35.                 'If none of the operation matched, call default statement  
36.                 Console.WriteLine(" Please enter only define operation With Capital letter")  
37.         End Select  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

38.         Console.WriteLine("Press any key to exit...")  
39.         Console.ReadKey()  
40.     End Sub  
41. End Module   

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:

In the above example, we defined Select with multiple case statements, and if the user-defined input is
matched with any defined case statement, it executes that statement. And if the condition is not matched
with any case, it executes a default statement in VB.NET.

Here, we provide 'M' as input, which checks all case statements, and if any case is matched with M, it
executes the statement within the respective Case statement.

VB.NET Nested Select Case statements


When a Select Case statement is written inside the body of another Select Case statement is called
a nested Select Case statement.

Syntax:

1. Select Case "num"  
2. ' code to be executed if num = 1  
3. Case 1  
4. ' nested Select case  
5.      Select Case n  
6.           
7.                                  ' code to be executed if n = 5  
8.                                   Case 5  
9.                                  Statement 1  
10.                                   
11.                                 ' code to be executed if n = 10  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

12.                                  Case 10  
13.                                  Statement 2  
14.                                    
15.                                   ' code to be executed if n = 15  
16.                                   Case 15  
17.                                  Statement 3  
18.   
19.                                ’code to be executed if n doesn't match with any cases.  
20.                                Case Else  
21.                                 Statement  
22.   
23.            ' code to be executed if num = 2  
24.             Case 2  
25.             Statement 2  
26.              
27.             ' code to be executed if num = 3  
28.             Case 3  
29.            Statement 3  
30.              
31.             ' code to be executed if num doesn't match with any cases.  
32.             Case Else  
33.            Statement  

Example 1: Write a program to use a nested select case statement in VB.NET.

Module1.vb

1. Module Module1  
2.   
3.     Sub Main()  
4.   
5.         Dim x As Integer = 10, y As Integer = 5  
6.         Select Case x  
7.   
8.             Case 10  
9.                 Console.WriteLine("X Value: 10")  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

10.   
11.   
12.                 Select Case y  
13.                     Case 5  
14.                         Console.WriteLine("Nested Switch Value: 5")  
15.   
16.    
17.                         Select Case y - 2  
18.                             Case 3  
19.                                 Console.WriteLine("Another Nested Switch Value: 3")  
20.   
21.                         End Select  
22.                 End Select  
23.    
24.             Case 15  
25.                 Console.WriteLine("X Value: 15")  
26.   
27.             Case 20  
28.                 Console.WriteLine("X Value: 20")  
29.   
30.             Case Else  
31.                 Console.WriteLine("Not Known")  
32.   
33.         End Select  
34.         Console.WriteLine("Press Enter Key to Exit..")  
35.         Console.ReadLine()  
36.     End Sub  
37. End Module  

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Example 2: Write a program to use the nested select case statement in VB.NET.

nested_selectcase.vb

1. Imports System  
2. Module nested_selectcase  
3.     Sub Main()  
4.         Dim num As Integer  
5.         Dim str As String  
6.         str = "F"  
7.   
8.         Console.WriteLine(" Enter only First three number like 1, 2, 3")  
9.         num = Console.ReadLine() 'take input from the user  
10.         Select Case num  
11.             Case 1  
12.                 Console.WriteLine(" You are in block 1")  
13.                 Console.WriteLine("Only First two letter such as A and B")  
14.   
15.                 str = Console.ReadLine()  
16.                 Select Case str  
17.                     Case "A", "a"  
18.                         Console.WriteLine(" This is a VB.NET Tutorial")  
19.                     Case "B", "b"  
20.                         Console.WriteLine(" Welcome to the JavaTpoint")  
21.                     Case Else  
22.                         Console.WriteLine(" Something is wrong")  
23.                 End Select  
24.   
25.             Case 2  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

26.                 Console.WriteLine(" You are in block 2")  
27.                 Console.WriteLine("Only First two letter such as C and D")  
28.                 str = Console.ReadLine()  
29.                 Select Case str  
30.                     Case "C", "c"  
31.                         Console.WriteLine(" Welcome to the World!")  
32.                     Case "D", "d"  
33.                         Console.WriteLine(" Want to go in Heaven")  
34.                     Case Else  
35.                         Console.WriteLine(" Something is wrong")  
36.                 End Select  
37.   
38.             Case 3  
39.                 Console.WriteLine(" You are in block 3")  
40.                 Console.WriteLine("Only First two letter such as E and F")  
41.                 str = Console.ReadLine()  
42.                 Select Case str  
43.                     Case "E", "e"  
44.                         Console.WriteLine(" VB.NET is a programming language to develop web, window, and cons
ole-based application. ")  
45.                     Case "F", "f"  
46.                         Console.WriteLine(" You have to basic knowledge of c and c++")  
47.                     Case Else  
48.                         Console.WriteLine(" Something is wrong")  
49.                 End Select  
50.             Case Else  
51.                 Console.WriteLine(" Something is wrong")  
52.         End Select  
53.         Console.ReadLine()  
54.     End Sub  
55. End Module  

Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

In the above example, we have only defined the first three numbers 1-3 and if the number matches to any
case statement, the select statement is executed. Here, we have entered 2 that is matched with case 2 and
it executes a block as shown above. And this block executes the statement "Only the First two letters such
as C and D". Therefore, we enter a letter D, letter D is matched with the nested select case statement, and if
a match is found, it executes the select case statement as shown above.

VB.NET Do Loop
A Loop is used to repeat the same process multiple times until it meets the specified condition in a
program. By using a loop in a program, a programmer can repeat any number of statements up to the
desired number of repetitions. A loop also provides the suitability to a programmer to repeat the
statement in a program according to the requirement. A loop is also used to reduce the
program complexity, easy to understand, and easy to debug.

Advantages of VB.NET loop

o It provides code iteration functionality in a program.


o It executes the statement until the specified condition is true.
o It helps in reducing the size of the code.
o It reduces compile time.

Types of Loops
There are five types of loops available in VB.NET

:
o Do While Loop
o For Next Loop
o For Each Loop
o While End Loop
o With End Loop

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
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

, 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:

1. Do  
2. [ Statements to be executed]  
3. Loop While Boolean_expression  
4. // or  
5. Do   
6. [Statement to be executed]  
7. 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.

Flowchart of Do loop
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
The above flow chart represents the flow of Do While loop. It is used to control the flow of statements,
such that it executes the statement at least once before checking the While or Until condition. If the
condition is true, the next iteration will be executed till the condition become false.

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

1. Imports System  
2. Module Do_loop  
3.     Sub Main()  
4.         ' Initializatio and Declaration of variable i  
5.         Dim i As Integer = 1  
6.         Do  
7.             ' Executes the following Statement  
8.             Console.WriteLine(" Value of variable I is : {0}", i)  
9.             i = i + 1 'Increment the variable i by 1  
10.         Loop While i <= 10 ' Define the While Condition  
11.   
12.         Console.WriteLine(" Press any key to exit...")  
13.         Console.ReadKey()  
14.     End Sub  
15. End Module  

Now compile and execute the above program by clicking on the Start button, it shows the following
output:

In the above program, the Do While loop executes the body until the given condition becomes false.
When the condition becomes false the loop will be terminated.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
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

1. Imports System  
2. Module Do_loop  
3.     Sub Main()  
4.         ' Initialization and Declaration of variable i  
5.         Dim i As Integer = 1  
6.         Do  
7.             ' Executes the following Statement  
8.             Console.WriteLine(" Value of variable i is : {0}", i)  
9.             i = i + 1 'Increment variable i by 1  
10.         Loop Until i = 10 ' Define the Until Condition  
11.   
12.         Console.WriteLine(" Press any key to exit...")  
13.         Console.ReadKey()  
14.     End Sub  
15. End Module  

Output:

In the above program, a Do Until loop is executed their statement until the given condition Until (i =10) is
not meet. When the counter value of the variable i becomes 10, the defined statement will be false, and
the loop will be terminated.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Nested Do While Loop Statement
In VB.NET, when we use one Do While loop inside the body of another Do While loop, it is called Nested
Do While loop.

Syntax

1. Do  
2. // Statement of the outer loop  
3. Do  
4.            // Statement of outer loop  
5. While (condition -2)  
6. // Statement of outer loop  
7. While (condition -1)  

Example 2: Write a simple program to use the Do While loop Statement in VB.NET.

Nest_Do_While.vb

1. Imports System  
2. Module Nest_Do_While  
3.     Sub Main()  
4.         ' Declare i and j as Integer variable  
5.         Dim i As Integer = 1  
6.         Do  
7.             ' Outer loop statement  
8.             Console.WriteLine(" Execution of Outer loop is {0}", i & " times")  
9.               
10.             Dim j As Integer = 1  
11.   
12.             Do  
13.                 'Inner loop statement  
14.                 Console.WriteLine(" Execution of Inner loop is {0}", j)  
15.                 j = j + 1 ' Increment Inner Counter variable by 1  
16.             Loop While j < 3  
17.   
18.             Console.WriteLine()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

19.             i = i + 1 ' Increment Outer Counter variable by 1  
20.         Loop While i < 4  
21.         Console.WriteLine(" Exit from the loop")  
22.         Console.WriteLine(" Press any key to exit...")  
23.         Console.ReadKey()  
24.     End Sub  
25. End Module  

Output:

In the above example, each iteration of the outer loop also executes the inner loop repeatedly until the
inner condition becomes false. When the condition of the outer loop becomes false, the execution of the
outer and inner loop will be terminated.

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

1. For variable_name As [ DataType ] = start To end [ Step step ]  
2. [ Statements to be executed ]  
3. Next  

Let's understand the For Next loop in detail.

o For: It is the keyword that is present at the beginning of the definition.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

o variable_name: It is a variable name, which is required in the For loop Statement. The value of the
variable determines when to exit from the For-Next loop, and the value should only be a numeric.
o [Data Type]: It represents the Data Type of the variable_name.
o start To end: The start and end are the two important parameters representing the initial and final
values of the variable_name. These parameters are helpful while the execution begins, the initial
value of the variable is set by the start. Before the completion of each repetition, the variable's
current value is compared with the end value. And if the value of the variable is less than the end
value, the execution continues until the variable's current value is greater than the end value. And if
the value is exceeded, the loop is terminated.
o Step: A step parameter is used to determine by which the counter value of a variable is increased or
decreased after each iteration in a program. If the counter value is not specified; It uses 1 as the
default value.
o Statements: A statement can be a single statement or group of statements that execute during the
completion of each iteration in a loop.
o Next: In VB.NET a Next is a keyword that represents the end of the For loop's

Flowchart of For Next loop


The following flowchart represents the functioning of the For Next loop in the VB.NET programming
language.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
In the above flow chart, the first step is to initialize the variable name with the start value. And then, the
value of the variable will be compared to the end expression or value. If the condition is true, the control
enters the loop body and executes the statements. After that, the value of a variable will be automatically
incremented by the compiler. Upon completion of each iteration, the current value of a variable will
be again compared to the end expression. If the condition is not true, the controlled exit from the loop.

Example 1. Write a simple program to print the number from 1 to 10 using the For Next loop.

Number.vb

1. Imports System  
2. Module Number  
3.     Sub Main()  
4.         ' It is a simple print statement, and 'vbCrLf' is used to jump in the next line.  
5.         Console.Write(" The number starts from 1 to 10 " & vbCrLf)  
6.         ' declare and initialize variable i  
7.         For i As Integer = 1 To 10 Step 1  
8.             ' if the condition is true, the following statement will be executed  
9.             Console.WriteLine(" Number is {0} ", i)  
10.             ' after completion of each iteration, next will update the variable counter  
11.         Next  
12.         Console.WriteLine(" Press any key to exit... ")  
13.         Console.ReadKey()  
14.     End Sub  
15. End Module  

Output:

In the above example, we have initialized an integer variable i with an initial value 1. The For loop will
continuously execute its body until the value of i is smaller or equal to 10. After each iteration, the value
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
of i is automatically increased with 'Step 1'. If the value of i reached 10, the loop would be terminated and
control transfer to the Main() function.

Further, we can change the Step in For Next loop. Write the following program to skip the number is 2.

Number.vb

1. Imports System  
2. Module Number  
3.     Sub Main()  
4.         ' declaration of variable i  
5.         Dim i As Integer  
6.         Console.Write(" Skip one number at the completion of each iteration in between 1 to 10 " & vbCrLf)  
7.         ' initialize i to 1 and declare Step to 2 for skipping a number  
8.         For i = 1 To 10 Step 2  
9.             ' if condition is true, it skips one number  
10.             Console.WriteLine(" Number is {0} ", i)  
11.             ' after completion of each iteration, next will update the variable counter to step 2  
12.         Next  
13.         Console.WriteLine(" Press any key to exit... ")  
14.         Console.ReadKey()  
15.     End Sub  
16. End Module   

Output:

As we can see in the above output, the value of the variable i is initialized with 1, and the value of i is
skipped by 'Step 2' in the loop for each iteration to print the skipped number from 1 to 10.

Example 2: Write a simple program to print a table in the VB.NET.

Table.vb

1. Imports System  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

2. Module Table  
3.     Sub Main()  
4.         'declaration of i and num variable  
5.         Dim i, num As Integer  
6.         Console.WriteLine(" Enter any number to print the table")  
7.         num = Console.ReadLine() ' accept a number from the user  
8.         Console.WriteLine(" Table of " & num)  
9.         'define for loop condition, it automatically initialize step to 1  
10.         For i = 1 To 10  
11.             Console.WriteLine(num & " * " & i & " = " & i * num)  
12.         Next  
13.         Console.ReadKey()  
14.     End Sub  
15. 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:

1. For variable_name As [Data Type] = start To end [ Step step ]  
2.     For variable_name As [Data Type] = start To end [ Step step ]  
3.         [ inner loop statements ]  
4.     Next  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

5.     [ Outer loop statements ]  
6. Next  

Following is the example of Nested For Next loop in VB.NET.

Nested_loop.vb

1. Imports System  
2. Module Nested_loop  
3.     Sub Main()  
4.         Dim i, j As Integer  
5.         For i = 1 To 3  
6.             'Outer loop  
7.             Console.WriteLine(" Outer loop, i = {0}", i)  
8.             'Console.WriteLine(vbCrLf)  
9.   
10.             'Inner loop  
11.             For j = 1 To 4  
12.                 Console.WriteLine(" Inner loop, j = {0}", j)  
13.             Next  
14.             Console.WriteLine()  
15.         Next  
16.         Console.WriteLine(" Press any key to exit...")  
17.         Console.ReadKey()  
18.     End Sub  
19. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

In the above example, at each iteration of the outer loop, the inner loop is repeatedly executed its entire
cycles until the condition is not satisfied.

Example 2: Write a program to print a pattern in VB.NET.

Pattern.vb

1. Imports System  
2. Module Pattern  
3.     Sub Main()  
4.         Dim i, n, j As Integer  
5.         Console.WriteLine(" Enter a number to show rows in a Pattern")  
6.         ' take a number from user  
7.         n = Console.ReadLine()  
8.   
9.         'Outer loop  
10.         For i = 1 To n  
11.             'Inner loop  
12.             'value of j should be less than i  
13.             For j = 1 To i  
14.                 Console.Write(" * ")  
15.             Next  
16.             Console.WriteLine("")  
17.         Next  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

18.         Console.WriteLine(" Press any key to exit...")  
19.         Console.ReadKey()  
20.     End Sub  
21. 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:

1. For Each var_name As [ DataType ] In Collection_Object  
2. [ Statements to be executed]  
3. 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.

Flowchart of For Each loop


The following flowchart represents the For Each Next loop's functioning to iterate through array elements
in the VB.NET programming language.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

The first step is to initialize an array or collection object to execute each element of the array with the help
of variables in For Each loop. A variable is used in For Each loop to checks whether the element is
available or not. If the element is available in the collection object, the For Each block will be executed until
the condition remains true. After the execution of each element of an array, the control transfer to the end
statement.

Examples of For Each Loop

Write a simple program to understand the uses of For Each Next loop in VB.NET.

For_Each_loop.vb

1. Imports System  
2. Module For_Each_loop  
3.     Sub Main()  
4.         'declare and initialize an array as integer  
5.         Dim An_array() As Integer = {1, 2, 3, 4, 5}  
6.         Dim i As Integer 'Declare i as Integer  
7.   
8.         For Each i In An_array  
9.             Console.WriteLine(" Value of i is {0}", i)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

10.         Next  
11.         Console.WriteLine("Press any key to exit...")  
12.         Console.ReadLine()  
13.     End Sub  
14. End Module  

Output:

In the above example, we create an integer array with the name An_array (), and For Each loop is used to
iterate each element of the array with the help of defined variable 'i'.

Example 2: Write a simple program to print fruit names using For Each loop in VB.NET.

For_each.vb

1. Imports System  
2. Module For_each  
3.     Sub Main()  
4.         'Define a String array  
5.         Dim str() As String  
6.   
7.         'Initialize all element of str() array  
8.         str = {"Apple", "Orange", "Mango", "PineApple", "Grapes", "Banana"}  
9.   
10.         Console.WriteLine("Fruit names are")  
11.   
12.         'Declare variable name as fruit   
13.         For Each fruit As String In str  
14.             Console.WriteLine(fruit)  
15.         Next  
16.         Console.WriteLine(" Press any key to exit...")  
17.         Console.ReadKey()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

18.     End Sub  
19. End Module  

Output:

In this example, str() is a String type array that defines different fruits names. And fruit is the name of a
variable that is used to iterate each element of the str() array using For Each loop in the program. If all the
element is read, control passes to the Main() function to terminate the program.

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:

1. While [condition]  
2.     [ Statement to be executed ]  
3. 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.

Flow Diagram of the While End Loop in VB.NET


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

As we know, the While End loop is an entry-controlled loop used to determine if the condition is true,
the statements defined in the body of the loop are executed, and the execution process continues till
the condition is satisfied. Furthermore, after each iteration, the value of the counter variable is
incremented. It again checks whether the defined condition is true; And if the condition is again true, the
body of the While loop is executed. And when the condition is not true, the control transferred to the end
of the loop.

Example: Write a simple program to print the number from 1 to 10 using while End loop in VB.NET.

while_number.vb

1. Imports System  
2. Module while_number  
3.     Sub Main()  
4.         'declare x as an integer variable  
5.         Dim x As Integer  
6.         x = 1  
7.         ' Use While End condition  
8.         While x <= 10  
9.             'If the condition is true, the statement will be executed.  
10.             Console.WriteLine(" Number {0}", x)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

11.             x = x + 1 ' Statement that change the value of the condition  
12.         End While  
13.         Console.WriteLine(" Press any key to exit...")  
14.         Console.ReadKey()  
15.     End Sub  
16. End Module  

Output:

In the above example, while loop executes its body or statement up to the defined state (i <= 10). And
when the value of the variable i is 11, the defined condition will be false; the loop will be terminated.

Example 2: Write a program to print the sum of digits of any number using while End loop in VB.NET.

Total_Sum.vb

1. Public Class Total_Sum ' Create a Class Total_sum  
2.     Shared Sub Main()  
3.         'Declare an Integer variable  
4.         Dim n, remainder, sum As Integer  
5.         sum = 0  
6.   
7.         Console.WriteLine(" Enter the number :")  
8.         n = Console.ReadLine()  ' Accept a number from the user  
9.   
10.         ' Use While loop and write given below condition    
11.         While (n > 0)  
12.             remainder = n Mod 10  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

13.             sum += remainder  
14.             n = n / 10  
15.         End While  
16.         Console.WriteLine(" Sum of digit is :{0}", sum)  
17.         Console.WriteLine(" Press any key to exit...")  
18.         Console.ReadKey()  
19.     End Sub  
20. End Class  

Output:

Nested While End Loop


In VB.NET, when we write a While End loop inside the body of another While End loop, it is called Nested
While End loop.

Syntax

1. While (condition -1)  
2. // body of the outer while loop  
3. While (condition -2)  
4.                      // body of inner while loop  
5. End While  
6. // body of the outer loop  
7. End While  

Write a program to understand the Nested While End loop in VB.NET programming.

Nest_While.vb

1. Imports System  
2. Module Nest_While  
3.     Sub Main()  
4.         ' Declare i and j as Integer variable  
5.         Dim i As Integer = 1  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

6.   
7.   
8.         While i < 4  
9.             ' Outer loop statement  
10.             Console.WriteLine(" Counter value of Outer loop is {0}", i)  
11.             Dim j As Integer = 1  
12.   
13.             While j < 3  
14.                 'Inner loop statement  
15.                 Console.WriteLine(" Counter value of Inner loop is {0}", j)  
16.                 j = j + 1 ' Increment Inner Counter variable by 1  
17.             End While  
18.             Console.WriteLine() 'print space  
19.             i = i + 1   ' Increment Outer Counter variable by 1  
20.         End While  
21.         Console.WriteLine(" Press any key to exit...")  
22.         Console.ReadKey()  
23.     End Sub  
24. End Module  

Output:

In the above example, at each iteration of the outer loop, the inner loop is repeatedly executed its entire
cycles until the inner condition is not satisfied. And when the condition of the outer loop is false, the
execution of the outer and inner loop is terminated.

VB.NET With End With Statement


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
In VB.NET, the With End statement is not the same as a loop structure. It is used to access and execute
statements on a specified object without specifying the name of the objects with each statement. Within
a With statement block, you can specify a member of an object that begins with a period (.) to define
multiple statements.

Syntax:

1. With objExpression  
2.     [ Statements to be Executed]  
3. End With  

objExpression: It defines the data type of objExpression. It may be any class or structure type or basic
data type such as Integer. It can be executed once in the With End statement.

Statement: It defines one or more executed statements within the With block. The statement refers to the
member of the object that links with objectExpression to execute the With statement block.

End With: It is used to end the With block.

Example: Write a program to understand the uses of With End statement in VB.NET.

Employee.vb

1. Public Class Employee  
2.     ' definition of global variables  
3.     Public Property name As String  
4.     Public Property age As Integer  
5.     Public Property Occupation As String  
6.     Public Property email As String  
7.   
8.     Shared Sub Main()  
9.         ' Create an emp object   
10.         Dim emp As New Employee  
11.         ' To define the member of an object  
12.         With emp  
13.             .name = " Mr. Stephen"  
14.             .age = 33  
15.             .Occupation = "Data Analyst"  
16.             .email = "[email protected]"  
17.         End With  
18.         With emp  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

19.             ' use emp as a reference  
20.             Console.WriteLine(" Name is : {0}", .name)  
21.             Console.WriteLine(" Age is : {0}", .age)  
22.             Console.WriteLine(" Occupation is : {0}", .Occupation)  
23.             Console.WriteLine(" Employee Email is : {0}", .email)  
24.         End With  
25.         Console.WriteLine(" Press any key to exit...")  
26.         Console.ReadKey()  
27.     End Sub  
28. End Class  

Output:

Example: Write a program to display the student details using the With End statement in VB.NET.

With_Statement.vb

1. Imports System  
2. Module With_statement  
3.     Sub Main()  
4.         ' Create a stud object   
5.         Dim stud As Student = New Student()  
6.   
7.         ' To define the member of an object using With Statement  
8.         With stud  
9.             .stud_name = " Mr. Robert"  
10.             .stud_course = "Computer Science"  
11.             .stud_rollno = "01"  
12.         End With  
13.           
14.         With stud  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

15.             ' use stud as a reference  
16.             Console.WriteLine(" Student Name is : {0}", .stud_name)  
17.             Console.WriteLine(" Student Course Name is : {0}", .stud_course)  
18.             Console.WriteLine(" Student RollNo. is : {0}", .stud_rollno)  
19.         End With  
20.         Console.WriteLine(" Press any key to exit...")  
21.         Console.ReadKey()  
22.     End Sub  
23.   
24.     ' Create a Class Student  
25.     Public Class Student  
26.         Public stud_name As String 'Define the variable of a class  
27.         Public stud_course As String  
28.         Public stud_rollno As Integer  
29.     End Class  
30. End Module  

Output:

VB.NET Exit Statement


In VB.NET, the Exit statement is used to terminate the loop (for, while, do, select case, etc.) or exit the
loop and pass control immediately to the next statement of the termination loop. Furthermore, the Exit
statement can also be used in the nested loop to stop or terminate the execution of the inner or outer
loop at any time, depending on our requirements.

Syntax

1. Exit { Do | For | Function |    Property | Select | Sub | Try | While }  

The flow of Exit Statement


Following is the diagrammatical representation of Exit Statement in VB.NET programming language.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Generally, the Exit statement is written along with a condition. If the Exit condition is true inside the loop,
it exits from the loop and control transfer to the next statement, followed by the loop. And if
the Exit condition fails for the first time, it will not check any statement inside the loop
and terminates the program.

We will now see how to use the Exit statement in loops and Select case statements to finish the program's
execution in the VB.NET programming language.

Use of Exit statement in While End loop


Example 1: Write a simple program to use the Exit Statement in While End loop.

Exit_While.vb

1. Imports System  
2. Module Exit_While  
3.     Sub Main()  
4.         ' Definition of count variable  
5.         Dim count As Integer = 1  
6.   
7.         ' Execution of While loop  
8.         While (count < 10)  
9.             ' Define the Exit condition using If statement  
10.             If count = 5 Then  
11.                 Exit While ' terminate the While loop   
12.             End If  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

13.             Console.WriteLine(" Value of Count is : {0}", count)  
14.             count = count + 1  
15.         End While  
16.         Console.WriteLine(" Exit from the While loop when count = {0}", count)  
17.         Console.WriteLine(" Press any key to exit...")  
18.         Console.ReadKey()  
19.     End Sub  
20. End Module  

Output:

In the above example, the While End loop is continuously executed, its body until the given
condition While (count < 10) is not satisfied. But when the Exit condition (count = 5) falls inside a while
loop, the execution of the loop is automatically terminated, and control moves to the next part of the loop
statement.

Use of Exit statement in For Next loop


Example 2: Write a program to calculate the sum of 10 numbers, and if a negative number is entered,
the For Each loop ends.

1. Imports System  
2. Module Exit_For  
3.     Sub Main()  
4.         'Definition of num variable  
5.         Dim num As Integer  
6.         Dim sum As Double = 0.0  
7.   
8.         'Execution of For loop  
9.         For i As Integer = 1 To 10  
10.             'Accept a number from the user  
11.             Console.WriteLine("Enter a number : ")  
12.             num = Console.ReadLine()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

13.             ' If the user enters a negative number, the loop terminates  
14.             If num < 0 Then  
15.                 Exit For ' terminate the For loop   
16.             End If  
17.             sum += num  
18.         Next  
19.           
20.         Console.WriteLine(" Exit from the For loop when (num < 0) is: {0}", num)  
21.         Console.WriteLine(" Total sum is : {0}", sum)          
22.         Console.WriteLine(" Press any key to exit from the Console Screen")  
23.         Console.ReadKey()  
24.     End Sub  
25. End Module  

Output:

The above program accepts a number from the user until it encounters a negative or less than 0 (num <
0). And when there is a negative number, the Exit statement terminates the loop, and the control transfer
to the next part of the loop.

Use of Exit statement in Do While loop


Example 3: Write a simple program to use the Exit Statement in Do While Loop.

Exit_Do_While.vb

1. Imports System  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

2. Module Exit_Do_While  
3.     Sub Main()  
4.         'Definition of the count variable  
5.         Dim count As Integer = 20  
6.   
7.         ' Definition of Do While loop  
8.         Do  
9.             'Define the Exit condition using If statement.  
10.   
11.             If count = 25 Then  
12.                 Exit Do ' terminate the Do While loop   
13.             End If  
14.             Console.WriteLine(" Value of Count is : {0}", count)  
15.             count = count + 1  
16.         Loop While (count < 50)  
17.         Console.WriteLine(" Exit from the Do While loop when count = {0}", count)  
18.         Console.WriteLine(" Press any key to exit...")  
19.         Console.ReadKey()  
20.     End Sub  
21. End Module  

Output:

In the above example, the Do While loop is continuously executed, its body until the given condition While
(count < 50) is not satisfied. But when the Exit condition (count = 25) is encountered, the Do While loop
is automatically terminated. The control is immediately transferred to the next statement, followed by the
loop statements.

VB.NET Continue Statement


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
In VB.NET, the continue statement is used to skip the particular iteration of the loop and continue with
the next iteration. Generally, the continue Statement is written inside the body of the For, While and Do
While loop with a condition. In the previous section, we learned about the Exit Statement. The main
difference between the Exit and a Continue Statement is that the Exit Statement is used to exit or
terminate the loop's execution process. In contrast, the Continue Statement is used to Skip the particular
iteration and continue with the next iteration without ending the loop.

Syntax:

1. Continue { Do | For | While }  

Flow Diagram of Continue Statement


Following is the pictorial representation of the Continue Statement in VB.NET programming language.

In the above diagram, a Continue Statement is placed inside the loop to skip a particular statement or
iteration. Generally, a continue statement is used with a condition. If the condition is true, it skips the
particular iteration and immediately transfers the control to the beginning of the loop for the execution of
the next iteration.

Now we will see how to use the Continue statement in the loop to skip the execution of the code and send
the control to the beginning of the loop to execute further statements in the VB.NET programming
language.

Use of Continue statement in While End loop


Example 1: Write a simple program to use the Continue Statement in While End loop.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Continue_While.vb

1. Imports System  
2. Module Continue_While  
3.     Sub Main()  
4.         'Declaration and initialization of variable i  
5.         Dim i As Integer = 10  
6.   
7.         'Define the While Loop Condition  
8.         While i < 20  
9.   
10.             If i = 14 Then  
11.                 Console.WriteLine(" Skipped number is {0}", i)  
12.                 i += 1 ' skip the define iteration  
13.                 Continue While  
14.             End If  
15.             Console.WriteLine(" Value of i is {0}", i)  
16.   
17.             i += 1 ' Update the variable i by 1  
18.         End While  
19.         Console.WriteLine(" Press any key to exit...")  
20.         Console.ReadKey()  
21.     End Sub  
22. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
In the above program, the While loop is continuously executed, their body until the given condition  ( i <
20) is met. But when the value of i is equal to 15, the Continue statement is encountered. It skips the
current execution and transfers the control to the beginning of the loop to display the next iteration.

Use of Continue statement in For Next loop


Example 2: Write a simple program to print the number from 10 to 1 with Continue Statement in  For Next
loop.

Continue_For.vb

1. Imports System  
2. Module Continue_For  
3.     Sub Main()  
4.         'Declaration and initialization of variable i, num  
5.         Dim i As Integer = 10  
6.         Dim num As Integer  
7.         'Define the For Loop Condition  
8.         For i = 10 To 1 Step -1  
9.   
10.             If i = 5 Then ' if i = 5, it skips the iteration   
11.                 num = i 'Assign the skip value to num variable  
12.                 Continue For ' Continue with Next Iteration  
13.             End If  
14.             Console.WriteLine(" Value of i is {0}", i)  
15.   
16.         Next  
17.         Console.WriteLine(" Skipped number is {0}", num)  
18.         Console.WriteLine(" Press any key to exit...")  
19.         Console.ReadKey()  
20.     End Sub  
21. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

In the above program, the For loop is continuously decremented their body until the variable i is  1. But
when the value of i is equal to 5, the Continue Statement is encountered. Then it skips
the current execution and transfers control to the beginning of the loop to display the next iteration.

Use of Continue statement in Do While loop


Example 3: Write a simple program to Understand the use of Continue Statement in Do While loop.

Continue_Do_While.vb

1. Imports System  
2. Module Continue_Do_While  
3.     Sub Main()  
4.         'Declaration and initialization of local variable  
5.         Dim i As Integer = 10, num As Integer  
6.   
7.         'Definition the Do While Loop  
8.         Do  
9.             If i = 14 Then  
10.                 num = i  
11.                 i += 1 ' skip the define iteration  
12.                 Continue Do  
13.             End If  
14.             Console.WriteLine(" Value of i is {0}", i)  
15.   
16.             i += 1 ' Update the variable i by 1  
17.         Loop While i < 20  
18.         Console.WriteLine(" Skipped number is {0}", num)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

19.   
20.         Console.WriteLine(" Press any key to exit...")  
21.         Console.ReadKey()  
22.     End Sub  
23. End Module  

Output:

In the above program, the Do loop is continuously executed their body until the given condition ( i <
20) is met. But when the value of i is equal to 15, the Continue Statement is encountered. It skips the
current execution and transfers the control to the beginning of the loop to display the next iteration.

VB.NET GoTo Statement


In VB.NET, the GoTo statement is known as a jump statement. It is a control statement that transfers the
flow of control to the specified label within the procedure. The GoTo statement uses labels that must be a
valid identifier. The GoTo statement can be used in Select case, decision control statements, and loops.

Syntax:

1. GoTo label_1  

Here, GoTo is a keyword, and label_1 is a label used to transfer control to a specified label statement in a
program.

Now we will see how to use the GoTo statement in the loop, select case, or decision-making statement to
transfer control to the specified label statement in the VB.NET program.

Use of GoTo statement in If Else


Example 1: Write a simple program to print whether the number is even or odd in GoTo Statement.

Goto_Statement.vb
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

1. Imports System  
2. Module Goto_Statement  
3.     Sub Main()  
4.         'Declaration of local variable  
5.         Dim num As Integer  
6.         Console.WriteLine(" Enter the number :")  
7.         num = Console.ReadLine ' Accept a number from the user  
8.         If (num Mod 2 = 0) Then  
9.             GoTo even ' Jump to even label  
10.         Else  
11.             GoTo odd   ' Jump to odd label  
12.         End If  
13. odd:  
14.         Console.WriteLine(" It is an Odd number")  
15.   
16. even:  
17.         Console.WriteLine(" It is an Even number ")  
18.         Console.WriteLine(" Press any key to exit...")  
19.         Console.ReadKey()  
20.     End Sub  
21. End Module  

Output:

In the above program, when we enter a number, it checks whether the number is even or odd. And if the
number is odd, the GoTo statement will be encountered, and the control transfers to the odd
statement Else the control transfer to the even statement.

Use of GoTo Statement in For Next loop


Example 2: Write a program to print the sum of the First ten numbers using the Goto Statement
in VB.NET.

Goto_For.vb
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

1. Imports System  
2. Module Goto_For  
3.     Sub Main()  
4.         'Declaration of local variable  
5.         Dim i, n As Integer, Sum As Integer = 0  
6.   
7.         ' Define For Loop Statement  
8.         For i = 1 To 10  
9.             Console.WriteLine(" Value of i is {0}", i)  
10.             Sum = Sum + i 'At each iteration the value of i added to Sum  
11.             If i = 5 Then  
12.                 n = i 'Assign i to n  
13.   
14.                 GoTo total_sum  ' Jump to total_sum  
15.             End If  
16.         Next  
17. total_sum:  
18.         Console.WriteLine(" Total sum is {0}", Sum)  
19.         Console.WriteLine(" GoTo Encounter, when value of i = {0}", n)  
20.         Console.WriteLine(" Press any key to exit...")  
21.         Console.ReadKey()  
22.     End Sub  
23. End Module  

Output:

In the above program, the For loop is executed till the given condition ( i = 1 To 10). And when the value
of i is equal to 5, the GoTo statement will be encountered, and it transfers the control to total_sum so
that the total sum of each iteration can be printed in the For loop.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Use of GoTo statement in Select Case Statement
Example 3: Write a simple program to print the days' names in select cases using the GoTo Statement.

Goto_Select.vb

1. Imports System  
2. Module Goto_Select  
3.     Sub Main()  
4.         'Definition of local variable   
5.         Dim Days As String  
6.         Days = "Thurs"  
7.         Select Case Days  
8.   
9.             Case "Mon"  
10. Case1:  
11.   
12.                 Console.WriteLine(" Today is Monday")  
13.             Case "Tue"  
14.                 Console.WriteLine(" Today is Tuesday")  
15.             Case "Wed"  
16.                 Console.WriteLine("Today is Wednesday")  
17.             Case "Thurs"  
18.                 Console.WriteLine("Today is Thursday")  
19.                 GoTo Case1  
20.             Case "Fri"  
21.                 Console.WriteLine("Today is Friday")  
22.             Case "Sat"  
23.                 Console.WriteLine("Today is Saturday")  
24.             Case "Sun"  
25.                 Console.WriteLine("Today is Sunday")  
26.             Case Else  
27.                 Console.WriteLine(" Something wrong")  
28.   
29.         End Select  
30.         Console.WriteLine("You have selected : {0}", Days)  
31.         Console.WriteLine("Press any key to exit...")  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

32.         Console.ReadLine()  
33.     End Sub  
34. End Module  

Output:

In the Select case statement, the value of Days Thurs will compare the values of all selected cases available
in a program. If it matches any statement, it prints the particular statement and contains the GoTo
statement that transfers control to defined case1: and then the following statement is executed.

Use of GoTo statement in While End Loop Statement


Example 4: Write a simple program to understand the use of GoTo statement in the While loop.

Goto_While.vb

1. Imports System  
2. Module GoTo_While  
3.     Sub Main()  
4.         'Declaration and initialization of the local variable  
5.         Dim i As Integer = 1, num As Integer  
6. start1:  
7.         'Definition of While Loop  
8.         While i < 10  
9.             If i = 6 Then  
10.                 num = i  
11.                 i += 1  
12.                 GoTo start1 'transfer control at start1  
13.             End If  
14.             Console.WriteLine(" Value of i is {0}", i)  
15.   
16.             i += 1 ' Update the variable i by 1  
17.         End While  
18.         Console.WriteLine(" Control transfer at number {0}", num)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

19.   
20.         Console.WriteLine(" Press any key to exit...")  
21.         Console.ReadKey()  
22.     End Sub  
23. End Module  

Output:

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:

1. Enum enumeration name [ As Data type ]  
2. ' enumeration data_list or Enum member list  
3. End Enum   

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:

1. Enum Fruits  
2. Banana  
3. Mango  
4. Orange  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

5. Pineapple  
6. Apple  
7. 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.

1. Enum Fruits  
2. Banana = 5  
3. Mango  
4. Orange  
5. Pineapple  
6. Apple  
7. 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

1. Imports System  
2. Module Enum_Data  
3.     Enum Number   
4.     ' List of enumerated data  
5.         One  
6.         Two  
7.         Three  
8.         Four  
9.         Five  
10.         Six  
11.     End Enum  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

12.     Sub Main()  
13.         Console.WriteLine(" Without the index number")  
14.       Console.WriteLine(" Number {0}", Number.One) 'call with enumeration and items name   
15.         Console.WriteLine(" Number {0}", Number.Two)  
16.         Console.WriteLine(" Number {0}", Number.Three)  
17.         Console.WriteLine(" Number {0}", Number.Four)  
18.         Console.WriteLine(" Number {0}", Number.Five)  
19.         Console.WriteLine(" Number {0}", Number.Six)  
20.         Console.WriteLine(" Press any key to exit...")  
21.         Console.ReadKey()  
22.     End Sub  
23. End Module  

Output:

In the above example, an enumerator "Number" that gets each value of the enumerated data such as
"Number.One", etc. to print the list.

Get an integer value from Enum


To get the integer value of the enumerator items from a list in VB.NET. We can use an
explicit CInt() method to get the Enum data index value is an integer. For example, the following
statement shows how to change an Enum item value using CInt () to convert from Enum to Integer.

1. Dim x As Integer = CInt(Fruits.Orange)  
2. Dim y As Integer = CInt(Fruits.Apple)  

Here, Fruits is the name of enumerator data and the Orange, and Apple is the name of element define in
the enumerator list to access the index number of the items.

Example 2: Write a program to set and access the index number using the Enum in VB.NET.

Enum_month.vb
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

1. Imports System  
2. Module Enum_month  
3.     Enum Monthname 'Enumeration name  
4.         January = 1  
5.         February  
6.         march  
7.         April  
8.         May  
9.         June  
10.         July  
11.         August  
12.         September = 10 'Set value to 10  
13.         October  
14.         November  
15.         December  
16.     End Enum  
17.     Sub Main()  
18.         Dim x As Integer = CInt(Monthname.June)  
19.         Dim y As Integer = CInt(Monthname.August)  
20.         Dim p As Integer = CInt(Monthname.September)  
21.         Dim q As Integer = CInt(Monthname.October)  
22.         Dim r As Integer = CInt(Monthname.December)  
23.   
24.         Console.WriteLine(" Month name is {0}", Monthname.January)  
25.         Console.WriteLine(" Index number is  " & Monthname.January)  
26.         Console.WriteLine(" June Month name is in {0}", x & " Position")  
27.         Console.WriteLine(" August Month name is in {0}", y & vbCrLf & "Position")  
28.   
29.         Console.WriteLine(" After Setting a new value at the middle")  
30.         Console.WriteLine(" September Month name is {0}", p & " Position")  
31.         Console.WriteLine(" October Month name is {0}", q & " Position")  
32.         Console.WriteLine(" December Month name is {0}", r & " Position")  
33.         Console.WriteLine(" Press any key to exit...")  
34.         Console.ReadKey()  
35.   
36.     End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

37. End Module  

Output:

In the above example, we have assigned a new value to the first element of the enumeration list (January
= 1), and then the successive values of the list are incremented by 1. And in the middle, we have again set
a new value to the item (September = 10) to get each item's index value defined in the enumeration list.

VB.NET Enum Methods


The following methods are available in Enum class that contain various methods to work with an
enumeration (enum).

Methods Description

Format A Format method is used to convert an enum type value to a specified string
format.

GetName As the name suggests, the GetName function is used to get the specified item's
name from the enumeration list.

GetNames A GetNames method is used to retrieve all available names from a specified
enumeration list as an array.

GetValues As the name suggests, a GetValues method is used to obtain all values from a
specified enumeration list as an array.

Parse A parse method is used to convert a string representation of a name or


numeric value of one or more enumerated constants into an enumerated
object.

GetUnderlyingType It is used to return the type of the underlying item in a specified enumeration.

Use of loop in Enum


In VB.NET, we can use For or Foreach loop in enum to get the name or values of each item of an
enumerator list with enum helper methods.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Example 3: Write a simple program to get all the enumeration item names and values using the loop in
enum helper methods.

Enum_Flower.vb

1. Imports System  
2. Module Enum_Flower  
3.     Enum Flower 'Enumeration name containing the list  
4.         Rose  
5.         Lotus  
6.         Marigold  
7.         Tulip  
8.         Jasmine  
9.         Peony  
10.         Aster  
11.   
12.     End Enum  
13.     Sub Main()  
14.         Console.WriteLine(" Flower Enumeration Data values")  
15.         'Declaration of local variable i   
16.         For Each i As String In [Enum].GetNames(GetType(Flower)) 'use of GetNames method  
17.             Console.WriteLine(" Flower name is {0}", i)  
18.   
19.         Next  
20.         Console.WriteLine(" Press any key to exit...")  
21.         Console.ReadKey()  
22.     End Sub  
23. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

In the above program, the For Each loop is continuously executes their enumerated data values until the
list does not become empty. At each iteration, the value of the variable i is incremented, and
the GetNames function will get each item from the enumerated list and prints the enum item.

VB.NET String
In VB.NET, string is a sequential collection of characters that is called a text. The String keyword is used to
create a string variable that stores the text value. The name of the string class is System.String that
contains the various function of string.

Declaration and Initialization of String


The following are the different ways to declare and initialize the string variable using the String keyword in
the VB.NET programming language

1. 'Declaration of the String variable  
2. Dim str As String  
3. Dim abc As String  
4.   
5. ' Initialization of String variable  
6. Dim str As String = "Welcome to JavaTpoint."  
7. Dim str1 As String = "Hello World!"  
8.   
9. ' Initialize a null string  
10. Dim str2 As String = Nothing  
11.   
12. ' Initialization of an empty string  
13. Dim name As String = String.Empty   
14.   
15. ' Creating a String from char  
16. Dim letter As Char() = {"H", "E",  "L", "L", "O" }  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
In the above declaration of string, we have defined the string variable with string keyword

and initialize string variable with value based on our requirements.

Creating a String Object


There are different ways to create a string object in the String.

1. To use a String class constructor.


2. By using the property or calling method to return a string.
3. Use a string literal to define a string variable.
4. Use a String concatenation operator (+).
5. By using a formatting function to convert a value or object into the string representation of the
object.

Let's create an example to demonstrates the uses of String objects.

String_object.vb

1. Imports System  
2. Module String_object  
3.     Sub Main()  
4.         Dim str, str2, fullname, data As String  
5.         str = "Hello"  
6.         str2 = "World!"  
7.         fullname = str + " " + str2  
8.         Console.WriteLine(" Message is {0}", str)  
9.         Console.WriteLine(" Message is {0}", str2)  
10.         Console.WriteLine(" Fullname is {0}", fullname)  
11.   
12.         ' By using string constructor  
13.         Dim str3 As Char() = {"H", "e", "l", "l", "o"}  
14.         data = New String(str3)  
15.   
16.   
17.         Console.WriteLine(" Your message is {0}", data)  
18.   
19.         ' Use of returning string  
20.         Dim arr() As String = {" Hello", "Welcome", "to", "JavaTpoint"}  
21.         Dim msg As String = String.Join(" ", arr)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

22.         Console.WriteLine(" You have defined these parameters as string array {0}", msg)  
23.   
24.         'Use of Formatting method to convert a value to the string  
25.         Dim time As DateTime = New Date(2020, 6, 18, 18, 48, 2)  
26.         Dim sentmsg As String = String.Format(" Your message has been successfully sent at {0:t} on {0:D}", ti
me)  
27.         Console.WriteLine(" Your text is that {0}", sentmsg)  
28.         Console.WriteLine(" Press any key to exit...")  
29.         Console.ReadKey()  
30.     End Sub  
31. End Module  

Output:

Immutable string object


In VB.NET, the string object is immutable. It means that once we have created a string object, it cannot be
modified during its execution. And if we modified an existing value in a string object through addition and
subtraction, it discards the old value of instance in memory and creates a new instance to hold a new
value. Furthermore, if we want to perform any operation in the String object, we must define an object
every time to create a new String object. So, in that case, the string provides
the System.Text.StringBuilder class to modify a string without creating a new object.

Properties of the String Class


Following are the two properties of string class:

1. Chars: It is used to get the character from the current string object.
2. Length: It is used to return the number of characters in the current string object.

Access individual characters from Strings in VB.NET


In VB.NET, we can access the individual character from the current string object with index values.

Let's write a program to access the individual characters from the string by defining an index position.

Get_Chars.vb
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

1. Imports System  
2. Module Get_Chars  
3.     Sub Main()  
4.         Dim i As Integer  
5.         ' Declaration of String variable  
6.         Dim name As String = "Hello World!"  
7.         Console.WriteLine(" These are Characters in Hello World! String :")  
8.         For i = 0 To name.Length - 1 ' Count from 0 to Length - 1  
9.             Console.WriteLine(name(i))  
10.         Next  
11.         Console.WriteLine("Length is {0}", name.Length) ' Use of Length Properties  
12.         Console.WriteLine(" Press any key to exit...")  
13.         Console.ReadKey()  
14.     End Sub  
15. End Module   

Output:

In the above program, a For loop is continuously executed each element of the String variable's value
is Hello World! Until the condition (name.Length -1) is reached. Here, Length function is used to count
the number of characters in the string.

There are various functions of string class that helps to manipulate the string objects.

1. Compare(): It is used to compare two specified string objects, and if the string is less than another
string object, it returns an integer value.

Syntax:

1. Public Shared Function Compare ( str1 As String, Str2 As String ) As Integer  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
The returned integer value represents the relationship between two specified string objects. The following
table shows the string comparison condition that returns the integer value after comparing two specified
string items.

Compare String Condition It returns an integer value

Str1 == Str2 0

Str1 > Str2 1

Str1 < Str2 -1

Example: Write a program to understand the uses of Compare() function in String Class.

String_cmp.vb

1. Imports System.String  
2. Module String_cmp  
3.     Sub Main()  
4.         'Definition of local String variable  
5.         Dim Str1 As String = "Hello"  
6.         Dim Str2 As String = "Cello"  
7.         ' Use of String.compare() function  
8.         Console.WriteLine(" Comparison of String {0} and {1} result is {2}", Str1, Str2, String.Compare(Str1, Str2
))  
9.   
10.         Dim Sdata As String = " WELCOME"  
11.         Dim Sdata2 As String = " Welcome"  
12.         ' Use of String.Compare() function  
13.         Console.WriteLine(" Comparison result of String {0} and {1} result is {2}", Sdata, Sdata2, String.Compar
e(Sdata, Sdata2))  
14.   
15.         Dim Sdata3 As String = "Hello"  
16.         Dim Sdata4 As String = "Hello"  
17.         ' Use of String.Compare() function  
18.         Console.WriteLine(" Comparison result of String {0} and {1} result is {2}", Sdata3, Sdata4, String.Compa
re(Sdata3, Sdata4))  
19.   
20.         Console.WriteLine(" Press any key to exit...")  
21.         Console.ReadKey()  
22.     End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

23. End Module  

Output:

In the above example, the string compare () method checks the values of two string variables and returns
integer values.

2. Concat()

The Concat() function is used in string class to join two or more strings or append one string to the end of
another string. It is useful when we need to combine two or more text to make a sentence, and it returns a
new string.

Syntax:

1. Public Shared Function Concat( Str1 As String, str2 As String ) As String  

And when we use more than three string parameters to combine, we have to define this way:

Syntax:

1. Public Shared Function Concat( Str1 As String, Str2 As String, Str3 As String ) As String  

Let's create a program to understand the uses of the Concat() function to append or concatenate one or
more strings in the VB.NET programming language.

String_concate.vb

1. Imports System.String  
2. Module String_concate  
3.     Sub Main()  
4.         ' Definition of local variables  
5.         Dim str As String = "Learn"  
6.         Dim Str2 As String = " " & "VB.NET Programming Language"  
7.         'Use of Concat() function to combine two string variable  
8.         Console.WriteLine("Your String is {0}", String.Concat(str, Str2))  
9.   
10.         Dim val As String = "Want to"  
11.         Dim val2 As String = " " & "Learn String methods"  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

12.         Dim str3 As String = " " & "in VB.NET language?"  
13.         'Use of Concat() function to combine two or more string variable  
14.   
15.         Console.WriteLine("Your Sentence is {0}", String.Concat(String.Concat(val, val2), str3))  
16.         Console.WriteLine(" Press any key to exit...")  
17.         Console.ReadKey()  
18.     End Sub  
19. End Module  

Output:

In the above program, we used a Concat() function to combine one or more strings to return a single
string.

3. Contains(): It is used to validate whether the specified text or parameter exists in the current string. If
the text is existing in the string, it returns a true Boolean value; otherwise, it returns false.

Syntax:

1. Public Shared Function Contains ( text As String ) As Boolean  

Let's create a program to understand the uses of the Contains() function to check whether the particular
string exists or not in a given string.

String_contain.vb

1. Imports System.String  
2. Module String_contain  
3.     Sub Main()  
4.         'Definition of local variables  
5.         Dim msg As String = "Welcome to VB.NET Language."  
6.         Dim txt As String = "VB.NET"  
7.   
8.         ' Use of Contains() function  
9.         Console.WriteLine("Does {0} String Contains {1}? :{2}", msg, txt, msg.Contains(txt))  
10.   
11.         Dim str As String = "String is the collection of characters."  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

12.         Dim strtxt As String = "Collection"  
13.   
14.         'Use of Contains function  
15.         Console.WriteLine("Does {0} Sentence Contains {1}? :{2}", str, strtxt, str.Contains(strtxt))  
16.   
17.         Console.WriteLine(" Press any key to exit...")  
18.         Console.ReadKey()  
19.     End Sub  
20. End Module  

Output:

In the above program, the String Contains() function is to determine whether the given string str contains
the value of strtext, and if the value exists in the str, it returns a true value; otherwise, it returns false.

4. String Copy(): In the String class, there is a Copy() function used to create a new string object with the
same content or value specified in the original string.

Syntax:

1. Public Shared Function Copy (str1 As String ) As String  

Let's create a program to understand the uses of Copy() function in the VB.NET programming language.

String_copy.vb

1. Imports System.String  
2. Module String_Copy  
3.     Sub Main()  
4.         'Declaration and Initialization of local variable  
5.         Dim str As String = " Welcome to JavaTpoint"  
6.         ' Use String.Copy() function  
7.         Dim str2 As String = String.Copy(str)  
8.         Console.WriteLine(" Text in First String is {0}", str)  
9.         Console.WriteLine(" Copy text is {0}", str2)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

10.   
11.         ' Use String.Copy() function  
12.         Console.WriteLine("Text in Copy String : {0}", String.Copy(str))  
13.         Console.WriteLine(" Does the Object reference equal? {0}", Object.ReferenceEquals(str, str2))  
14.   
15.         Console.WriteLine(" Press any key to exit...")  
16.         Console.ReadKey()  
17.     End Sub  
18. End Module  

Output:

5. CopyTo(): A CopyTo () function is used to copy the specified number of characters from the original
string object.

Syntax:

1. Public Sub CopyTo( sourceIndex As Integer, destination As Char(), destinationIndex As Integer, count As Int
eger )  

Create a simple program of the CopyTo() function to copy a string in the VB.NET programming language.

String_CopyTo.vb

1. Imports System.String  
2. Module String_CopyTo  
3.     Sub Main()  
4.       ' Declaration of String variable  
5.         Dim data As String = "Welcometojavatpoint"  
6. ' Declaration of strcpy array  
7.         Dim strcpy(25) As Char  
8.         Console.WriteLine("Original String is: {0}", data)  
9.     ' use CopyTo() method  
10.         data.CopyTo(9, strcpy, 0, 10)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

11.         Console.WriteLine("Copied character is " + strcpy)  
12.         Console.WriteLine(" Press any key to exit...")  
13.         Console.ReadKey()  
14.     End Sub  
15. End Module  

Output:

6. EndsWith(): The EndsWith() function is used to check whether the text or parameter specified in the


original string ended with the specified text.

Syntax:

1. Public Function EndsWith( ByVal As String ) As Boolean  

Let's create a program to understand the uses of EndsWith() function in the VB.NET programming
language.

String_With.vb

1. Imports System.String  
2. Module String_With  
3.     Sub Main()  
4.         'Definition of String variable  
5.         Dim str As String  
6.         str = " VB.NET is the best programming language"  
7.         ' Use of EndsWith() function in String Class  
8.         If str.EndsWith("language") = True Then  
9.             Console.WriteLine(" The String statement EndsWith 'language'")  
10.         Else  
11.             Console.WriteLine(" The string is not EndsWith 'Language'")  
12.         End If  
13.         Console.WriteLine(" Press any key to exit...")  
14.         Console.ReadKey()  
15.     End Sub  
16. End Module  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Output:

In the above program, the EndsWith() function is checked whether the defined text 'language' specified


in the original string object str ends with the word language.

7. Equals(): As the name defines, an Equals() function is used in the string class to determine if both string
objects have the same value or not. If the value is the same, the Equals() string methods are true;
otherwise, it returns false. And if both objects have null values, the Equals() function returns a true value.

Syntax:

1. Public Function Equals ( ByVal A As String, ByVal B As String ) As Boolean  

Let's create a program to understand the uses of EndsWith() function in the VB.NET programming
language.

Equal_String.vb

1. Imports System.String  
2. Module Equal_String  
3.     Sub Main()  
4.         'Definition of local variable  
5.         Dim str = "Welcome"  
6.         Dim str2 = "welcome"  
7.         'Use of Equals() function  
8.         Console.WriteLine("Are string {0} and {1} equal? : {2}", str, str2, String.Equals(str, str2))  
9.         Dim str3 = "Welcome"  
10.         Console.WriteLine("Are string {0} and {1} equal? : {2}", str, str3, String.Equals(str, str3))  
11.         Console.WriteLine(" Press any key to exit...")  
12.         Console.ReadKey()  
13.     End Sub  
14. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

In the above example, the String Equals() method checks whether the specified strings object is equal. If
yes, it returns True value; otherwise, it returns False.

8. String Format(): The Format() function is used to replace one or more objects with the specified string
object. By using the Format() function, we can insert the value of a variable into another object string.

Syntax:

1. Public Function Format( Format_object As String, arg0 As Object ) As String  

Let's create a program to understand the uses of Format() function in the VB.NET programming language.

String_Format.vb

1. Imports System.String  
2. Module String_Format  
3.     Sub Main()  
4.         ' Declaration and Represntation of Format String  
5.         Dim rep_string As String = " Tutorial: {0}, Topic: {1}, Method Name: {2} "  
6.   
7.         'Use of String.Format() function  
8.         Dim spec_string As String = String.Format(rep_string, "VB.NET", "String", "Format_String")  
9.   
10.         Console.WriteLine(" Representation of String is {0}", spec_string)  
11.         Console.WriteLine(" Press any key to exit...")  
12.         Console.ReadKey()  
13.     End Sub  
14. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
In the above example, the string Format() method has replaced the format objects {0} with "VB.NET", {1}
with "String" and {2} with "Format_String".

9. IndexOf(): The String IndexOf() function is used to return the index position of the first occurrence of
the specified character or string in the original string object, followed by the zero (0) index. Furthermore,
we can also define the starting index position of the specified character or string in the original string.

Syntax:

1. 'Getting a Char:  
2. Public Function IndexOf( ByVal As Char ) As Integer  
3.   
4. 'For Getting a String:  
5. Public Function IndexOf( ByVal As String ) As Integer  
6.   
7. 'Define the starting position of the character  
8. Public Function IndexOf( ByVal As Char, StartIndex As Integer ) As Integer  
9.   
10. 'Define the starting position of the String  
11. Public Function IndexOf( ByVal As String, StartIndex As Integer ) As Integer  

Let's create a program to understand the uses of IndexOf() function in VB.NET programming language.

indexOf_String.vb

1. Imports System.String  
2. Module indexOf_String  
3.     Sub Main()  
4.         Dim Str As String = "JavaTpoint"  
5.         Dim txt As String = "Welcome to JavaTpoint Site"  
6.         ' Use of IndexOf() function to get specified character position  
7.         Console.WriteLine(" Occurrence of character T index position {0}", Str.IndexOf("T"))  
8.   
9.         ' Use of IndexOf() function to get the Specified String position of specified String  
10.         Console.WriteLine(" Occurrence of String position {0}", txt.IndexOf("JavaTpoint"))  
11.   
12.         'Starting position of p is 5  
13.         Console.WriteLine(" Define the starting position of the Character p is {0}", Str.IndexOf("p", 5))  
14.   
15.         'Starting position of JavaTpoint is 5  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

16.         Console.WriteLine(" Define the starting position of the String 'JavaTpoint' is {0}", txt.IndexOf("JavaTpoi
nt", 11, 15))  
17.   
18.         Console.WriteLine(" Press any key to exit...")  
19.         Console.ReadKey()  
20.     End Sub  
21. End Module  

Output:

In the above example, we used an IndexOf() function to get the specified position of a character or string
from the original string in VB.NET programming.

10. Insert(): The Insert() function of the String class is used to insert a specified string at the specified
position in the original string object.

Syntax:

1. Public Function Insert (StartIndex As Integer, ByVal As String ) As String  

Let's create a program to understand the uses of Insert() function in the VB.NET programming language.

String_Insert.vb

1. Imports System.String  
2. Module String_Insert  
3.     Sub Main()  
4.         Dim name = " Welcome to Site"  
5.         Dim str_name = "JavaTpoint"  
6.         'Use of Insert() function  
7.         Console.WriteLine(" Inserted String {0} into Original string is {1}", str_name, name.Insert(11, " JavaTpoi
nt"))  
8.         Console.WriteLine(" Press any key to exit...")  
9.         Console.ReadKey()  
10.     End Sub  
11. End Module  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Output:

11. Remove(): The remove function is used to remove or delete characters at the specified position until
the end of the defined string object. Furthermore, we can use the remove () function to remove a set of
characters by defining the beginning and end positions of the characters to be removed from the original
string.

Syntax:

1. Remove Single Character  
2. Public Function Remove( StartIndex As Integer ) As String  
3. Set of Character  
4. Public Function Remove( StartIndex As Integer, Length As Integer) As String   

Let's create a program to understand the uses of Insert() function in the VB.NET programming language.

String_Remove.vb

1. Module String_Remove  
2.     Sub Main()  
3.         Dim str As String = " Welcome to JavaTpoint Site"  
4.         ' For Single Character  
5.         Console.WriteLine(" Remove a Single character {0}", str.Remove(3))  
6.   
7.         ' For Group of character  
8.         Console.WriteLine(" Remove a set of character from the original String {0}", str.Remove(1, 3))  
9.         Console.WriteLine(" Press any key to exit...")  
10.         Console.ReadKey()  
11.     End Sub  
12. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

12. Replace(): The String Replace() function is used to replace all the occurrence of a specified character or
string from the original string object and then return a new string.

Syntax:

1. // Get the replace char  
2. Public Function Replace ( oldValue As Char, newChar As Char ) As String  
3. // Get the replace String  
4. Public Function Replace (oldValue As String, newValue As String) As String  

Let's create a program to understand the use of Replace() function in the VB.NET programming language.

String_Replace.vb

1. Imports System.String  
2. Module String_Replace  
3.     Sub Main()  
4.   
5.         Dim ch As String = "abababab"  
6.         'Use Replace() function to replace Single Character  
7.         Dim strchar As String = ch.Replace("a", "c")  
8.         Console.WriteLine(" Old Value is {0}", ch)  
9.         Console.WriteLine(" New Value is {0}", strchar)  
10.   
11.         Dim str As String = "It's Okay not to be Okay"  
12.         'Use Replace() function to replace String  
13.         Dim nstr As String = str.Replace("Okay", "Fine")  
14.         Console.WriteLine(" Old String is {0}", str)  
15.         Console.WriteLine(" New String is {0}", nstr)  
16.   
17.         Console.WriteLine(" Press any key to exit...")  
18.         Console.ReadKey()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

19.     End Sub  
20. End Module  

Output:

In the above example, we used a Replace() function to replace a specified character or string from the
given string in the VB.NET programming.

13. Join(): As the name suggests, a Join() function is used to concatenate all the specified elements of the
string array using the specified separator.

Syntax

1. Public Shared Function Join ( Separator As String, paramArray Value As String() ) As String  

Let's create a program to understand the uses of Join() function in the VB.NET programming language.

String_Join

1. Imports System.String  
2. Module String_Join  
3.     Sub Main()  
4.         Dim strArray() As String = {"Hello", "Welcome", "to", "JavaTpoint", "Site"}  
5.         'Use of String.Join() function  
6.         Dim strSep As String = String.Join("-", strArray)  
7.         Console.WriteLine(" Join String using the Hypen: {0}", strSep)  
8.   
9.         Dim textArray() As String = {"want to learn", "VB.NET programming Language", "?", "Join", "the JavaTp
oint Site"}  
10.         'Use the String.Join() function with Space (vbCrLf) Seperator    
11.   
12.         Console.WriteLine(" Text is {0}", String.Join(vbCrLf, textArray))  
13.         Console.WriteLine(" Press any key to exit...")  
14.         Console.ReadKey()  
15.   
16.     End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

17. End Module  

Output:

In the above program of String Join() function, we used hyphen (-) and comma (,) separator to


concatenates all the elements of the string array.

14. Split(): As the name suggests, the string Split() function is used to split a given string into substrings
with the help of delimiters that are used to split a string in VB.NeT programming language. Furthermore,
we can specify the number of characters that should be returned in the substring.

Syntax:

1. Public Function Split (ParamArray separator As Char() ) As String()  
2. ' Specifies the character length  
3. Public Function Split (ByVal separator As Char(), count As Integer) As String  

Let's create a program to understand the uses of the Split() function in the VB.NET programming
language.

String_Split.vb

1. Imports System.String  
2. Module String_Split  
3.     Sub Main()  
4.         Dim str As String = "Welcome-to-JavaTpoint"  
5.         'Use of Split() function  
6.         Dim txtArray As String() = str.Split(New Char() {"-"c})  
7.         For i As Integer = 0 To txtArray.Length - 1  
8.   
9.             Console.WriteLine(txtArray(i))  
10.         Next  
11.         Console.WriteLine(" Press any key to exit...")  
12.             Console.ReadKey()  
13.     End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

14. End Module  

Output:

In the above example, we used a Split() function to split the given string (Welcome-to-JavaTpoint") with a
separator hyphen (-), and it returns a split string as an array. And the For loop is used to display each item
of an array element.

15. StartsWith(): The StartsWith() function of String class is used to determine whether the string's
beginning is matched with a specified string object. If the string is matched, it returns True value;
otherwise, it shows False.

Syntax:

1. Public Function StartsWith ( ByVal As String ) As  Boolean  

Let's create a program to understand the uses of StartsWith() function in the VB.NET programming
language.

String_StartsWith.vb

1. Imports System.String  
2. Module String_StartsWith  
3.     Sub Main()  
4.         Dim str As String = "Welcome to JavaTpoint"  
5.         Dim stwith As String = "Welcome"  
6.         Dim st As String = "to"  
7.         ' Use of StartsWith() function  
8.         Console.WriteLine(" String is {0}", str)  
9.         Console.WriteLine(" Does the string start with '{0}'? : {1}", stwith, str.StartsWith(stwith))  
10.         Console.WriteLine(" Does string start with '{0}'? : {1}", st, str.StartsWith(st))  
11.         Console.WriteLine(" Press any key to exit...")  
12.         Console.ReadKey()  
13.     End Sub  
14. End Module  
15. Output:  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

16.  String is Welcome to JavaTpoint  
17.  Does the string start with 'Welcome'? : True  
18.  Does string start with 'to'? : False  
19.  Press any key to exit...  

In the above program, we used StartsWith() function to validate whether the given string starts
with "Welcome". If yes, returns True; otherwise, it shows False.

16. ToLower: The ToLower function of String class is used to convert any string object into Lower Case.

1. Public Function ToLower As String  

17. ToUpper: The ToUpper function of String class is used to convert a string object into Upper Case.

1. Public Function ToUpper As String  

Let's create a program to understand the uses of ToLower and ToUpper function in the VB.NET
programming language.

String_cases.vb

1. Imports System.String  
2. Module String_cases  
3.     Sub Main()  
4.         Dim str As String = "javatpoint"  
5.         Dim txt As String = " VB.NET TUTORIAL"  
6.         'Use ToUpper and ToLower method in String Class  
7.         Console.WriteLine("String converted into Upper Case is {0}", str.ToUpper)  
8.         Console.WriteLine("String converted into Lower Case is {0}", txt.ToLower)  
9.         Console.WriteLine(" Press any key to exit...")  
10.         Console.ReadKey()  
11.     End Sub  
12. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
In the above program, we used ToLower and ToUpper method in String class to convert a given string
into the Upper and Lower case of the VB.NET programming.

18. Trim(): The Trim() Function is used to remove all occurrence of leading and trailing whitespace,
characters and special symbols from the specified string object.

Syntax:

1. Public Function Trim() As String  
2. Public Function Trim( trimChars As Char()) As String  

The First Syntax of Trim() function represents that it is used to remove all whitespaces from the starting
and end of the given string.

The Second Syntax represents that it is used to trim all specified characters from the starting and end of
the given string object.

Let's create a program to understand the uses of the Trim() function in the VB.NET programming language.

Trim.vb

1. Imports System.String  
2. Module Trim  
3.     Sub Main()  
4.         Dim txt As String = "   VB.NET is the       "  
5.         Dim ttxt As String = "   Best Tutorial   "  
6.         Console.WriteLine(" Before Trim the String {0} {1}", txt, ttxt)  
7.         'Use of Trim() Function to remove WhiteSpace  
8.         Console.WriteLine(" After Trimming {0} {1}", txt.Trim(), ttxt.Trim())  
9.   
10.         'Definition of Char() Array  
11.         Dim trimChar As Char() = {"$c", "@", "&", "#"}  
12.         Dim str As String = "$$## VB.NET is the Best Tutorial &&&@@@"  
13.         Console.WriteLine(" Before Trim : {0}", str)  
14.         ' USe of Trim() function to remove character  
15.         Console.WriteLine(" After Trim : {0}", str.Trim(trimChar))  
16.         Console.WriteLine(" Press any key to exit...")  
17.         Console.ReadKey()  
18.     End Sub  
19. End Module  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Output:

VB.NET ArrayList
Collection Classes
The collection classes are special-purpose classes that are useful for storing data, dynamically allocating
memory, retrieving a list of items or elements on the basic index number, etc. Furthermore, the collection
classes also support Lists, ArrayList, Hash tables, queues, stacks, etc. that apply to the same interface.

ArrayList
The arrayList is an ordered collection of data elements that can be indexed individually in a list. The flexible
data structure allows multiple objects to be added in a list without any size information. It is similar to the
array. With the use of indexes in the ArrayList, we can add or remove an element from the list's specified
location. Further, it also allows search, sort, add, and dynamic memory allocation in the ArrayList.

Uses of ArrayList
The following are the important uses of the ArrayList object.

1. Add: Add a data element to ArrayList.

Syntax:

1. ArrayList.add(Element)  

2. Insert: Insert data element at specified location of ArrayList.

Syntax:

1. ItemList.Insert(index, "element_name")  

3. Remove: Remove an element from ArrayList.

Syntax:

1. ArrayList.Remove(element)  

4. RemoveAt: Remove data elements from the specified location of ArrayList.

Syntax:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

1. ArrayList.RemoveAt(indexNo)  

indexNo: It represents the specified position of the item to be removed from the ArrayList.

5. Sort(): As the name suggests, it is used to sort all elements of the ArrayList.

Syntax:

1. ArrayListSort()  

Properties of the ArrayList Class


Following are the property of the ArrayList Class in the VB.NET

Property name Description

Capacity It is used to get all elements of the ArrayList.

IsFixedSize It gets a value that determines if the ArrayList has a fixed size.

Count It is used to count the number of elements available in the ArrayList.

IsReadOnly It returns the value that verifies if the ArrayList is read-only.

Item It is used to get or set an item at a specified position in the ArrayList.

Methods of the ArrayList class


Following are the various methods of the ArrayList Class in the VB.NET

Method Name and their description

1. Add() Method: The Add() function is used to add an item to the end of the ArrayList.

Syntax:

1. Public Overridable Function Add(ByVal As Object) As Integer  

2. Clear() Method: The Clear() method is used to clear all the elements from the ArrayList

Syntax:

1. Public Overridable Sub Clear()  

3. Insert() Method: The Insert() method is used to insert an element into the specified location of the
ArrayList.

Syntax:

1. Public Overridable Sub Insert(index As Integer, ByVal As Object)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
4. Contains() Method: The Contains() Method is used to check whether the specified element exists in the
ArrayList.

Syntax:

1. Public Overridable Function Contains(element As Object) As Boolean.  

5. Remove() Method: The Remove() Method is used to remove a specified element from the ArrayList.

Syntax:

1. Public Overridable Sub Remove(obj As Object)  

6. InsertRange() Method: The InsertRange() method is used to insert the collections of elements at the
specified location in the ArrayList.

Syntax:

1. Public Overridable Sub InsertRange (index As Integer, c As ICollection)  

7. RemoveRange() Method: The RemoveRange() method is used to set a range for removing the
elements from the ArrayList.

Syntax:

1. Public Overridable Sub RemoveRange(index As Integer, count As Integer)  

8. Reverse() Method: The Reverse() Method is used to reverse the order of the elements to the ArrayList.

Syntax:

1. Public Overridable Sub Reverse  

9. RemoveAt() Method: The RemoveAt() method is used to remove an array element from the specified
index of the ArrayList.

Syntax:

1. Public Overridable Sub RemoveAt(index As  Integer)  

Let's create a program to understand the various function of ArrayList in the VB.NET programming
language.

AList.vb

1. Imports System.Collections.ArrayList  
2. Module AList  
3.     Sub Main()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

4.         Dim arrList As ArrayList = New ArrayList()  
5.         Dim i As Integer  
6.         Console.WriteLine(" Added elements in the ArrayList")  
7.   
8.         ' Use of Add() function  
9.         arrList.Add(50)  
10.         arrList.Add(55)  
11.         arrList.Add(10)  
12.         arrList.Add(70)  
13.         arrList.Add(10)  
14.         arrList.Add(40)  
15.         arrList.Add(13)  
16.         For Each i In arrList  
17.             Console.WriteLine("{0}", i)  
18.         Next i  
19.         Console.WriteLine()  
20.   
21.   
22.         'Use of Count to count the total elements in the ArrayList  
23.         Console.WriteLine(" Total Elements = {0}", arrList.Count)  
24.   
25.         'Use of Capacity to check the element can be contained in ArrayList  
26.         Console.WriteLine(" Capacity of the ArrayList = {0}", arrList.Capacity)  
27.   
28.         Console.WriteLine("Sorted Elements in ArrayList:")  
29.         arrList.Sort()  ' Use of Sort() function  
30.   
31.         For Each i In arrList  
32.             Console.WriteLine(" {0} ", i)  
33.         Next i  
34.   
35.         ' Use of Remove() Function  
36.         Console.WriteLine(" Remove 13 from the ArrayList")  
37.         arrList.Remove(13)  
38.         For Each i In arrList  
39.             Console.WriteLine(" {0} ", i)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

40.         Next i  
41.   
42.         ' Use of RemoveAt() Function  
43.         Console.WriteLine(" Remove an item from a specified position [3]")  
44.         arrList.RemoveAt(3)  
45.         Console.WriteLine(" After Removing the item")  
46.         For Each i In arrList  
47.             Console.WriteLine(" {0} ", i)  
48.         Next i  
49.         Console.WriteLine()  
50.         Console.WriteLine(" Press any key to exit...")  
51.         Console.ReadKey()  
52.     End Sub  
53. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

VB.NET HashTable
A HashTable is used to store the collection of different types of data in key-value pairs. These table data
are organized based on the hash key. A HashTable is provided by the System.Collection namespace.
A Key is used to identify and access each element of the HashTable because each item in the HashTable
has a Key/value pair.

HashTable Properties
The following table describes the properties of the HashTable

Property Description
Name

IsSynchronized It is used to obtain a value that determines whether the HashTable is synchronized.

IsFixedSize It is used to obtain a value that determines whether a HashTable has a fixed size.

Count It is used to count the number of key/value pair elements available in the
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

HashTable.

IsReadOnly It is used to obtain a value that determines whether the HashTable is read-only.

Item It is used to get or set a value associated with the specified key.

Keys It is used to obtain a collection of keys in a HashTable.

Values It is used to obtain a collection of values in a HashTable.

HashTable Methods
The Following are the commonly used method of the HashTable in the VB.NET.

Methods Description
Name

Add It is used to add an element with the specified key and value into the HashTable.
Syntax: HashTable.Add(key, value)

ContainsKey It is used to check whether the specified key exists or not in HashTable.
Syntax: HashTable.ContainsKey(key)

ContainsValue It is used to check whether the specified value of the key is existing or not in
HashTable.
Syntax: HashTable.ContainsValue(value)

Remove The Remove function is used to remove the specified key with the corresponding
value.
Syntax: HashTable.Remove(Key)

Clear It is used to remove all the elements from the HashTable.

GetHash A GetHash is used to get the hash code of the specified key in HashTable/

Let's create a program to understand the concept of HashTable in the VB.NET programming language.

Array_Hash.vb

1. Imports System.Collections  
2. Module Array_Hash  
3.     Sub Main()  
4.         Dim hashTab As Hashtable = New Hashtable()  
5.         Dim j As DictionaryEntry  
6.         'Use of Add() function  
7.         hashTab.Add("str", "VB.NET")  
8.         hashTab.Add("05", "Peter")  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

9.         hashTab.Add("06", "Hamilton")  
10.         hashTab.Add("07", "Universe")  
11.         hashTab.Add("08", "Welcome")  
12.         hashTab.Add("09", 90)  
13.         hashTab.Add("site", "JavaTpoint")  
14.         hashTab.Add("planet", "Earth")  
15.   
16.         For Each j In hashTab  
17.             Console.WriteLine(" Key = {0}, Value = {1}", j.Key, j.Value)  
18.         Next j  
19.         Console.WriteLine()  
20.   
21.         ' Use of ContainsValue() function  
22.         If hashTab.ContainsValue("Earth") Then  
23.             Console.WriteLine(" Value 'Earth' is exist")  
24.         Else  
25.             Console.WriteLine(" Doesn't exist")  
26.         End If  
27.         Console.WriteLine(" Total keys in HashTable {0}", hashTab.Count)  
28.   
29.         'Display a Single item.  
30.         Console.WriteLine("Display a Single item is '{0}' from HashTab", hashTab("07"))  
31.   
32.         'Use of ContainsKey() function  
33.         'Console.WriteLine(" Is the key '05' exist : {0) ", hashTab("05"))  
34.   
35.         'Use of Remove() function  
36.         Console.WriteLine(" Remove key 07 from HashTab ")  
37.         hashTab.Remove("07")  
38.         For Each j In hashTab  
39.             Console.WriteLine(" Key = {0}, Value = {1}", j.Key, j.Value)  
40.         Next j  
41.   
42.         Console.WriteLine(" Press any key to exit")  
43.         Console.ReadKey()  
44.     End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

45. End Module  

Output:

VB.NET Stack
The stack is a homogeneous collection of elements used to store elements based on LIFO (Last-In First-
Out). Generally, the stack is useful for accessing elements from a collection of objects in the Last-In First-
Out style. Furthermore, it uses push and pop operations to get an insert element in the collection. Push
operation is used to insert items into the stack, and pop operation is used to retrieve items from the stack.
The last added item in the stack is retrieved first.

The following figure represents the push and pop operation in the VB.NET Stack.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

In the above diagram, the Pop represents the retrieval of the last item (4) from the stack, and the Push
represents the insertion of the item in the Stack.

Methods in VB.NET Stack


The following are the most commonly used methods of the Stack in VB.NET.

Method Name Description

Clear The Clear method is used to remove all elements from the Stack.
Syntax: Public Overridable Sub Clear

Contains It is used to check whether the element exists or not in Stack.


Syntax: Stack.Contains(element)

Peek The Peek method is used to return an element at the top of the elements in Stack.

Pop It is used to remove an item that' added to the last in Stack.


Syntax: Stack.Pop()

Push A Push method is used to insert an item at the top of the Stack.
Syntax: Stack.Push(item)

ToArray The ToArray method is used to create a copy of the Stack.

Let's create a program to understand the various operation of Stack in the VB.NET programming language.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Stack_Collection.vb

1. Imports System.Collections  
2. Module Stack_Collection  
3.     Sub Main()  
4.         ' Create and initialize a Stack  
5.         Dim St_col As Stack = New Stack()  
6.         ' Inserting item in the Stack using the Push() Operation  
7.         St_col.Push("JavaTpoint")  
8.         St_col.Push("VB.NET")  
9.         St_col.Push("Tutorial")  
10.         St_col.Push("Stack")  
11.         St_col.Push("Array")  
12.         St_col.Push(10)  
13.   
14.         ' Count all items of the Stack.  
15.         Console.WriteLine(" Total Number of Inserted Elements in Stack is : {0}", St_col.Count)  
16.         Console.WriteLine(" Elements of Stack are :")  
17.         For Each item In St_col  
18.             Console.WriteLine(item)  
19.         Next  
20.         Console.WriteLine()  
21.   
22.         ' Use of Contains() function  
23.         Console.WriteLine(" Is the Element 'Array' exists in Stack? : {0}", St_col.Contains("Array"))  
24.         Console.WriteLine(" Is the Element '5' exists in Stack? : {0}", St_col.Contains(5))  
25.         Console.WriteLine()  
26.   
27.         ' Use of Peek() function  
28.         Console.WriteLine(" Next value to be popped at the top in Stack is : {0}", St_col.Peek())  
29.         For Each item In St_col  
30.             Console.WriteLine(item)  
31.         Next  
32.         Console.WriteLine()  
33.         ' Use of Pop() function  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

34.         Console.WriteLine(" Remove elements from the Stack")  
35.         St_col.Pop()  
36.         St_col.Pop()  
37.         St_col.Pop()  
38.         St_col.Pop()  
39.         Console.WriteLine(" After removing elements from the stack")  
40.         For Each item In St_col  
41.             Console.WriteLine(item)  
42.         Next  
43.   
44.         Console.WriteLine(" Press any key to exit...")  
45.         Console.ReadKey()  
46.     End Sub  
47.   
48. End Module  

Output:

In the above program, we have used various methods of Stack class such as Push() method is used to
insert the elements into the Stack. The Contains() method is used to check whether the particular element
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
exists or not, Peep() method is used to put the particular element at the top of all elements in the stack,
and the Pop() method is used to remove the elements from the Stack.

VB.NET 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.

1. 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.

1. 'Store only Integer values  
2. Dim num As Integer() or Dim num(5) As Integer  
3. 'Store only String values  
4. Dim name As String() or Dim name(5) As String  
5. ' Store only Double values  
6. Dim marks As Double()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Initialization of VB.NET Array
In VB.NET, we can initialize an array with New keyword at the time of declaration. For example,

1. 'Declaration and Initialization of an array elements with size 6  
2. Dim num As Integer() = New Integer(5) { }  
3. Dim num As Integer() = New Integer(5) {1, 2, 3, 4, 5, 6}   
4. Initialize an array with 5 elements that indicates the size of an array  
5. Dim arr_name As Integer() = New Integer() {5, 10, 5, 20, 15}  
6. Declare an array  
7. Dim array1 As Char()  
8. array1 = New Char() {'A', 'B', 'C', 'D', 'E'}  

Furthermore, we can also initialize and declare an array using the following ways, as shown below.

1. Dim intData() As Integer = {1, 2, 3, 4, 5}  
2. Dim intData(5) As Integer  
3. Dim array_name() As String = {"Peter", "John", "Brock", "James", "Maria"}  
4. Dim misc() as Object = {"Hello friends", 16c, 12ui, "A"c}  
5. Dim Emp(0 to 2) As String  
6. Emp{0} = "Mathew"  
7. Emp(1) = " Anthony"  
8. Emp(2) = "Prince"  

Let's create a program to add the elements of an array in VB.NET programming language.

num_Array.vb

1. Imports System  
2. Module num_Array  
3.     Sub Main()  
4.         Dim i As Integer, Sum As Integer = 0  
5.         'In VB.NET the size of an array is n+1  
6.         'Declaration and Initialization of marks() array  
7.         Dim marks() As Integer = {58, 68, 95, 50, 23, 89}  
8.         Console.WriteLine(" Marks in 6 Subjects")  
9.         For i = 0 To marks.Length - 1  
10.             Console.WriteLine(" Marks {0}", marks(i))  
11.             Sum = Sum + marks(i)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

12.         Next  
13.         Console.WriteLine(" Grand total is {0}", Sum)  
14.   
15.         Console.WriteLine(" Press any key to exit...")  
16.         Console.ReadKey()  
17.     End Sub  
18. End Module  

Output:

In the above program, we create an integer array with name marks() and define a For loop to access each
item of the array marks.

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

1. Imports System  
2. Module Input_array  
3.     Sub Main()  
4.         'Definition of array  
5.         Dim arr As Integer() = New Integer(5) {}  
6.         For i As Integer = 0 To 5  
7.             Console.WriteLine(" Enter the value for arr[{0}] : ", i)  
8.             arr(i) = Console.ReadLine()  ' Accept the number in array   
9.         Next  
10.         Console.WriteLine(" The array elements are : ")  
11. ' Definition of For loop  
12.         For j As Integer = 0 To 5  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

13.   
14.             Console.WriteLine("{0}", arr(j))  
15.         Next  
16.   
17.         Console.WriteLine(" Press any key to exit...")  
18.         Console.ReadKey()  
19.     End Sub  
20. End Module  

Output:

Multidimensional Array
In VB.NET, a multidimensional array is useful for storing more than one dimension in a tabular form, such
as rows and columns. The multidimensional array support two or three dimensional in VB.NET.

Declaration of Multidimensional Array

1. Declaration of two-dimensional array  
2. Dim twoDimenArray As Integer( , ) = New Integer(3, 2) {}  
3. Or Dim arr(5, 3) As Integer  
4. Representation of Three Dimensional array  
5. Dim arrThree(2, 4, 3) As Integer  
6. Or Dim arr1 As Integer( , , ) = New Integer(5, 5, 5) { }  

In the above representation of multidimensional, we have created 2-dimensional array twoDimenArray


with 3 rows and 2 columns and 3-dimensional array with three dimensions 2, 4, and 3.

Initialization of Multidimensional Array


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
The following ways to initialize the multidimensional array:

1. ' Initialization of Two Dimensional Array  
2. Dim intArray As Integer( , ) = New Integer( 3, 2) { {4, 5}, {2, 3}, {6, 7} }  
3. Dim intArray( , ) As Integer = {  {5, 4}, {3, 2}, {4, 7} }  
4. ' Initialization of Three Dimensional Array  
5. Dim threeDimen(3, 3, 2 ) As Integer = { {{1, 3, 2}, {2, 3, 4}}, {{5, 3, 6}, {3, 4, 5}}, {{1, 2, 2}, {5, 2, 3} }}   

Multidimensional Array Example

Let's create a program to understand the multidimensional array.

MultidimenArray.vb

1. Imports System  
2. Module MultidimenArray  
3.     Sub Main()  
4.         ' Definition of 2 Dimensional Array  
5.         Dim intArray(,) As Integer = {{5, 4}, {3, 2}, {4, 7}, {4, 5}}  
6.   
7.         ' Definition of 3 Dimensional Array  
8.         Dim threeDimen(,,) As Integer =  
9.             {{{1, 3, 2}, {2, 3, 4}},  
10.             {{5, 3, 6}, {3, 4, 5}},  
11.         {{1, 2, 2}, {5, 2, 3}}}  
12.   
13.         Console.WriteLine(" Two Dimensional Arraye in VB.NET are")  
14.         For i As Integer = 0 To 3  
15.             For j As Integer = 0 To 1  
16.                 Console.WriteLine("intArray[{0}, {1}] = {2}", i, j, intArray(i, j))  
17.             Next j  
18.         Next i  
19.   
20.         Console.WriteLine(" Three Dimensional Arraye in VB.NET are")  
21.         For i As Integer = 0 To 2 - 1  
22.             For j As Integer = 0 To 2 - 1  
23.                 For k As Integer = 0 To 4  
24.                     Console.WriteLine("intArray[{0}, {1}, {2}] = {3}", i, j, k, threeDimen(i, j, k))  
25.                 Next k  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

26.             Next j  
27.         Next i  
28.   
29.         Console.WriteLine(" Press any key to exit...")  
30.         Console.ReadKey()  
31.     End Sub  
32. End Module  

Output:

Fixed Size Array


In VB.NET, a fixed- size array is used to hold a fixed number of elements in memory. It means that we have
defined the number of elements in the array declaration that will remain the same during the definition of
the elements, and its size cannot be changed. For example, we need to hold only 5 names in an array; it
can be defined and initialized in the array such as,

1. Dim names( 0 to 4) As String  
2. names(0) = "Robert"  
3. names(1) = "Henry"  
4. names(2) = "Rock"  
5. names(3) = "James"  
6. names(4) = "John"  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
The above representation of the fixed array is that we have defined a string array names 0 to 4, which
stores all the elements in the array from 0 to index 4.

VB.NET Queue
In VB.NET, the Queue is used to store a collection of objects that follow  FIFO (First In, First Out). Generally,
the Queue class is provided by the VB .NET collection, which is useful for accessing elements from a
collection of objects in the first-in-first-out style, which means the item inserted first in the queue will come
out first from the queue. Furthermore, it uses Enqueue() and Dequeue() operation to insert and delete
element from the collection of objects in Queue, where the Enqueue() operation is used to add elements
at the end of the queue, and the Dequeue() operation is used to remove items starting from the queue.

The following is the pictorial representation of the Enqueue and Dequeue process in the VB.NET Queue.

In this diagram, the Enqueue represents the Queue's insertion, and the Dequeue represents the deletion of
the items from the Queue.

Methods of VB.NET Queue


The following are the most commonly used methods of the Queue in VB.NET.

Method Name Description


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Clear A Clear is used to remove all elements from the Queue.


Public Overridable Sub Clear

Contains It is used to validate whether a particular element exists in Queue or not.


Syntax: Queue.Contains(element)

Peek A Peek method is used to return the first element out of the Queue.
Syntax: Queue.Peek()

Dequeue It is used to remove an item from the starting of a Queue.


Syntax Queue.Dequeue()

Enqueue An Enqueue method is used to insert an item at the end of the Queue.
Syntax: Queue.Enqueue(item)

Let's create a program to understand the various function of Queue in the VB.NET programming language.

Que_col.vb

1. Imports System.Collections  
2. Module Que_col  
3.     Sub Main()  
4.         ' Create and initialize a Queue  
5.         Dim q_col As Queue = New Queue()  
6.         ' Inserting items ino the Queue using the Enqueue() Operation  
7.         q_col.Enqueue("JavaTpoint")  
8.         q_col.Enqueue("VB.NET")  
9.         q_col.Enqueue("Tutorial")  
10.         q_col.Enqueue("Queue")  
11.         q_col.Enqueue("Array")  
12.         q_col.Enqueue(10)  
13.   
14.         ' Count all items of the Queue  
15.         Console.WriteLine(" Total Inserted Elements in Queue is : {0}", q_col.Count)  
16.         Console.WriteLine(" Elements of Queue are :")  
17.         For Each item In q_col  
18.             Console.WriteLine(item)  
19.         Next  
20.         Console.WriteLine()  
21.   
22.         ' Use of Contains() function  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

23.         Console.WriteLine(" Is the Element 'Array' exists in Queue? : {0}", q_col.Contains("Array"))  
24.         Console.WriteLine(" Is the Element '5' exists in Queue? : {0}", q_col.Contains(5))  
25.         Console.WriteLine()  
26.   
27.         ' Use of Peek() function  
28.         Console.WriteLine(" Next value to be popped out from the Queue is : {0}", q_col.Peek())  
29.         Console.WriteLine(" Next value to be popped out from the Queue is : {0}", q_col.Peek())  
30.   
31.         ' Use of Dequeue() function  
32.         Console.WriteLine(" Remove some elements from Queue")  
33.         Dim obj As Object  
34.         obj = q_col.Dequeue()  
35.         Console.WriteLine(" Removed Value is: {0}", obj)  
36.         obj = q_col.Dequeue()  
37.         Console.WriteLine(" Removed Value is: {0}", obj)  
38.   
39.         Console.WriteLine(" After removing elements from Queue ")  
40.         For Each item In q_col  
41.             Console.WriteLine(item)  
42.         Next  
43.   
44.         Console.WriteLine(" Press any key to exit...")  
45.         Console.ReadKey()  
46.     End Sub  
47. End Module   

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

VB.NET 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:

1. Dim array_name() As Integer  

Runtime Declaration of the VB.NET Dynamic array (Resizing)


Syntax:

1. 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

1. Dim myArr() As String  
2. ReDim myArr(3)  
3. myArr(0) = "One"  
4. myArr(1) = "Two"  
5. myArr(2) = "Three"  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

6. 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.

1. ReDim Preserve myArr(4)  
2. 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.

1. Dim myArr() As Variant  
2. ReDim myArr(3)  
3. myArr(0) = 10  
4. myArr(0) = "String"  
5. myArr(0) = false  
6. myArr(0) = 4.6   

Let's create a program to understand the dynamic array.

Dynamic_Arr.vb

1. Imports System  
2. Module Dynamic_Arr  
3.     Sub Main()  
4.         'Declaration and Initialization of String Array Days()  
5.         Dim Days(20) As String  
6.         ' Resize an Array using the ReDim Statement  
7.         ReDim Days(6)  
8.         Days(0) = "Sunday"  
9.         Days(1) = "Monday"  
10.         Days(2) = "Tuesday"  
11.         Days(3) = "Wednesday"  
12.         Days(4) = "Thursday"  
13.         Days(5) = "Friday"  
14.         Days(6) = "Saturday"  
15.   
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

16.         For i As Integer = 0 To Days.Length - 1  
17.             Console.WriteLine("Days Name in [{0}] index is {1}", i, Days(i))  
18.         Next  
19.         Console.WriteLine(" Press any key to exit...")  
20.         Console.ReadKey()  
21.     End Sub  
22. 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

1. Imports System  
2. Module Dynamic_arr1  
3.     Sub Main()  
4.         'Declaration and Initialization of String Array Days()  
5.         Dim Days() As String  
6.         ' Resize an Array using the ReDim Statement  
7.         ReDim Days(2)  
8.         Days(0) = "Sunday"  
9.         Days(1) = "Monday"  
10.         Days(2) = "Tuesday"  
11.         Console.WriteLine(" Before Preserving the Elements")  
12.         For i As Integer = 0 To Days.Length - 1  
13.             Console.WriteLine("Days Name in [{0}] index is {1}", i, Days(i))  
14.         Next  
15.         Console.WriteLine()  
16.   
17.         Console.WriteLine(" After Preserving 0 to 2 index Elements")  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

18.         ReDim Preserve Days(6)  
19.         Days(3) = "Wednesday"  
20.         Days(4) = "Thursday"  
21.         Days(5) = "Friday"  
22.         Days(6) = "Saturday"  
23.         For i As Integer = 0 To Days.Length - 1  
24.             Console.WriteLine("Days Name in [{0}] index is {1}", i, Days(i))  
25.         Next  
26.         Console.WriteLine(" Press any key to exit...")  
27.         Console.ReadKey()  
28.     End Sub  
29. End Module  

Output:

In the above program, we have created a dynamic array Days as a String that executes the first three
elements of Days such as Sunday, Monday, and Tuesday. we have also used a Preserve Keyword to keep
the existing elements of an array with new elements in dynamic array Days.

VB.NET NameValueCollection
The NameValueCollcetion class is similar to HashTable that stores a collection of different data items in
keys and associated values in string type. The class is provided by the System.Collection Namespace.
The NameValueCollection can store more than one value under a single key separated by a comma.

Properties of the NameValueCollection Class


The following are the commonly used property of NameValueCollection:

Property Description
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

name

AllKeys It is used to get all the keys in the NameValueCollection

Count It is used to count the number of key/value pair elements available in the
NameValueCollection.

IsReadOnly It is used to get or set a value that determines whether the NameValueCollection is
read-only.

Item It is used to get or set a value associated with the specified key in the
NameValueCollection.

Keys It is used to get all the keys that have instances in the NameValueCollection.

Values It is used to obtain a collection of values in a NameValueCollection.

NameValueCollection Methods
The following are the commonly used methods of NameValueCollection.

Methods Name Description

Add It is used to add an element with the specified name and value into the
NameValueCollection.
Syntax: NameValueCollection.Add(key, value)

Remove The Remove function is used to remove the specified key with the corresponding
value.
Syntax: HashTable.Remove(Key)

Clear() It is used to remove all entries from the NameValueCollection.

Get(String) A Get() function is used to obtain a particular value of the specified index from
the NameValueCollection that are comma-separated list.
Syntax: NameValueCollection.Get(Key)

HasKeys() A HasKeys() function is used to get a value that represents whether the
NameValueCollection has keys that are not null.
Syntax: NameValueCollection.HasKey()

GetValues(String) It is used to get all the values of a specified key or index from the
NameValueCollection.
Syntax: GetValues (ByVal str As String) As String()

Set() In NameValueCollection, a Set() function is used to set or overwrite the existing


value of the key.
Syntax: Set(String, String)

Equals() The Equals() function is used to validate whether the specified object matches the
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

current object.

Let us create a program to understand how we can add new elements to a NameVal array.

NameVal.vb

1. Imports System.Collections.Specialized  
2. Module NameVal  
3.     Sub Main()  
4.         'Defining an array NVCol As NameValueCollection  
5.         Dim NVCol As NameValueCollection = New NameValueCollection()  
6.         Dim key As String  
7.         'Use of Add() function  
8.         NVCol.Add("flower", "Rose")  
9.         NVCol.Add("flower", "Lotus")  
10.         NVCol.Add("flower", "Sunflower")  
11.         NVCol.Add("planet", "Earth")  
12.         NVCol.Add("planet", "Mars")  
13.         NVCol.Add("planet", "Mercury")  
14.         NVCol.Add("planet", "Jupiter")  
15.   
16.         For Each key In NVCol  
17.             Console.WriteLine("Key Name: {0} ", key)  
18.             Console.WriteLine("Elements are: {0} ", NVCol.Get(key))  
19.         Next  
20.         Console.WriteLine()  
21.   
22.         'Display the First Key  
23.         Console.WriteLine("Name of first Key is: {0}", NVCol.GetKey(1))  
24.   
25.         'Display the First value of Key using the GetValues(key)  
26.         Console.WriteLine("Value of first Key is: {0}", NVCol.GetValues(0))  
27.   
28.         Console.WriteLine(" Total keys in NameValueCollection {0}", NVCol.Count)  
29.         Console.WriteLine()  
30.   
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

31.         'Use of Remove() function  
32.         Console.WriteLine(" Remove key 'flower' from NameValueCollection ")  
33.         NVCol.Remove("flower")  
34.         For Each key In NVCol  
35.             Console.WriteLine("Current Key Name: {0} ", key)  
36.             Console.WriteLine("Current Key Elements are: {0} ", NVCol.Get(key))  
37.         Next  
38.         Console.WriteLine()  
39.   
40.         Console.WriteLine(" Press any key to exit")  
41.         Console.ReadKey()  
42.     End Sub  
43. End Module  

Output:

VB.NET List
The List class is used to store generic types of collections objects. By using a generic class on the list, we
can store one type of object. The List size can be dynamically different depending on the need of the
application, such as adding, searching or inserting elements into a list. A VB.NET List class is provided by
the System.Collection.Generic namespace.

Properties of the VB.NET List


The following are the commonly used properties of the List.

Property Description
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

name

Capacity It is used to obtain or set a number that indicates the number of elements can be
placed in a list.

Count It is used to count the number of elements available in the List.

Item It is used to get or set an item at a specified position of the List.

VB.NET List Methods


The following are the methods of VB.NET List class for performing various operations like add, search,
remove, sort.

Method Description

Add As the name represents, the Add() method is used to add an object at the end of the
List

AddRange It is used to add the elements of the specified collection to the end of the List.

Clear It is used to clear all records from the List.

Contains It is used to validate whether the specified object exists in the List or not.

CopyTo A CopyTo() method is used to copy all records of a list into a one-dimensional array.

Find A Find() method is used to search for a specified element from a list that matches the
defined state and returns the first occurrence.

FindAll A FindAll() method is used to fetch all the elements from a list that matches the
condition defined by the specified predicate.

Insert It is used to insert an element at the specified position of the List.

InsertRange It is used to insert all elements of a specified collection in a list start from a specified
location.

Remove By using the Remove() method, we can delete a specified element from the list.

RemoveAt By using the RemoveAt() method in a list, we can delete an element from the specified
location in a list.

Reverse The Reverse() method is used to reverse the order list of elements.

Sort A Sort() method is used to sort the elements of the list.

ToArray It is used to copy all the elements of the list to a new array object.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Let us create a program to understand how we can add new elements to a dynamic array in the VB.NET
programming language.

Ar_List.vb

1. Imports System.Collections.Generic  
2. Module Ar_List  
3.     Sub Main()  
4.         Dim Lt As List(Of Integer) = New List(Of Integer)()  
5.         Dim i As Integer  
6.         'Dim j As String  
7.         Console.WriteLine(" Added elements in List1")  
8.         ' Use of Add() function  
9.         Lt.Add(50)  
10.         Lt.Add(55)  
11.         Lt.Add(10)  
12.         'Lt.Add(70)  
13.   
14.         Dim Lt2 As List(Of String) = New List(Of String)()  
15.         Lt2.Add("Welcome")  
16.         Lt2.Add("to")  
17.         Lt2.Add("JavaTpoint")  
18.         Lt2.Add("Site")  
19.   
20.         'Access all element of List1  
21.         For Each i In Lt  
22.             Console.WriteLine("{0}", i)  
23.         Next i  
24.         Console.WriteLine("Total elements in list1: {0}", Lt.Count)  
25.         Console.WriteLine("Number of elements can be placed in list1: {0}", Lt.Capacity)  
26.         Console.WriteLine()  
27.   
28.         'Access all element of list2  
29.         Console.WriteLine(" Added elements in List2")  
30.         For Each j In Lt2  
31.             Console.WriteLine("{0}", j)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

32.         Next j  
33.         Console.WriteLine("Total elements in list2: {0}", Lt2.Count)  
34.         Console.WriteLine("Number of elements can be placed in list2: {0}", Lt2.Capacity)  
35.         Console.WriteLine()  
36.   
37.         'Use Remove() function to delete an element  
38.         Console.WriteLine("The 'Site' Element to be removed from the List2", Lt2.Remove("Site"))  
39.         'Retrieve using For Loop  
40.         For Each j In Lt2  
41.             Console.WriteLine("{0}", j)  
42.         Next j  
43.         Console.WriteLine("Press any key to exit...")  
44.         Console.ReadKey()  
45.     End Sub  
46. End Module  

Output:

Let us create a program to understand the Insert(), Contains(), Copy array to List, and Sort() function in the
VB.NET.

A_List2.vb

1. Imports System.Collections.Generic  
2. Module A_List2  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

3.     Sub Main()  
4.         Dim Lt As List(Of Integer) = New List(Of Integer)()  
5.         Dim i As Integer  
6.   
7.         Console.WriteLine(" Insert 60 and 5 in the List")  
8.         ' Use of Add() function  
9.         Lt.Add(50)  
10.         Lt.Add(55)  
11.         Lt.Add(10)  
12.         Lt.Add(70)  
13.   
14.         ' Insert an Item in the list  
15.         Lt.Insert(2, 60)  
16.         Lt.Insert(4, 5)  
17.         'Access all element of List1  
18.         For Each i In Lt  
19.             Console.WriteLine("{0}", i)  
20.         Next i  
21.         Console.WriteLine()  
22.   
23.         ' Use of Contains() Function to check an item is exit  
24.         If Lt.Contains("60") Then  
25.             Console.WriteLine(" Number '60' is exist in the List")  
26.         Else  
27.             Console.WriteLine(" Not exist")  
28.         End If  
29.   
30.         ' Copy array to list  
31.         Dim Str_Ar As String() = New String(4) {}  
32.         Str_Ar(0) = "Apple"  
33.         Str_Ar(1) = "Mango"  
34.         Str_Ar(2) = "Banana"  
35.         Str_Ar(3) = "Orange"  
36.         Dim ar_List As New List(Of String)(Str_Ar)  
37.   
38.         For Each St As String In Str_Ar  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

39.             Console.WriteLine(St)  
40.         Next  
41.   
42.         'Sort element of List  
43.         Lt.Sort()  
44.         Console.WriteLine(" Sorted Elements in the List:")  
45.         For Each i In Lt  
46.             Console.WriteLine("{0}", i)  
47.         Next i  
48.         Console.WriteLine("Press any key to exit...")  
49.         Console.ReadKey()  
50.     End Sub  
51. End Module  

Output:

VB.NET 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.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Defining a Function
The syntax to define a function is:

1. [Access_specifier ] Function Function_Name [ (ParameterList) ] As Return_Type  
2. [ Block of Statement ]  
3. Return return_val  
4. End Function  

Where,

o Access_Specifier: It defines the access level of the function such as public, private, or friend,
Protected function to access the method.
o Function_Name: The function_name indicate the name of the function that should be unique.
o ParameterList: It defines the list of the parameters to send or retrieve data from a method.
o Return_Type: It defines the data type of the variable that returns by the function.

The following are the various ways to define the function in a VB.NET.

1. Public Function add() As Integer  
2. ' Statement to be executed  
3. End Function  
4.   
5. Private Function GetData( ByVal username As String) As String  
6. ' Statement to be executed  
7. End Function  
8.   
9. Public Function GetData( ByVal username As String, ByVal userId As Integer) As String  
10. ' Statement to be executed  
11. End Function  

Example: Write a program to find the sum and subtraction of two numbers using the function.

Find_Sum.vb

1. Imports System  
2. Module Find_Sum  
3.     ' Create the SumOfTwo() Function and pass the parameters.  
4.     Function SumOfTwo(ByVal n1 As Integer, ByVal n2 As Integer) As Integer  
5.         ' Define the local variable.  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

6.         Dim sum As Integer = 0  
7.         sum = n1 + n2  
8.         Return sum  
9.     End Function  
10.     Function SubtractionOfTwo(ByVal n1 As Integer, ByVal n2 As Integer) As Integer  
11.         ' Define the local variable.  
12.         Dim subtract As Integer  
13.         subtract = n1 - n2  
14.         Return subtract  
15.     End Function  
16.     Sub Main()  
17.         ' Define the local variable a and b.  
18.         Dim a As Integer = 50  
19.         Dim b As Integer = 20  
20.         Dim total, total1 As Integer  
21.         Console.WriteLine(" First Number is : {0}", a)  
22.         Console.WriteLine(" Second Number is : {0}", b)  
23.         total = SumOfTwo(a, b) 'call SumOfTwo() Function  
24.         total1 = SubtractionOfTwo(a, b) 'call SubtractionOfTwo() Function  
25.         Console.WriteLine(" Sum of two number is : {0}", total)  
26.         Console.WriteLine(" Subtraction of two number is : {0}", total1)  
27.         Console.WriteLine(" Press any key to exit...")  
28.         Console.ReadKey()  
29.     End Sub  
30. End Module  

Output:

In the above example, we have defined a SumOfTwo() and SubtractionOfTwo() function to add and
subtract two predefined numbers. When the functions are called in the main() method, each function is
executed and returns the sum and subtraction of two numbers, respectively.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Example: Write a program to reverse a number and check whether the given number is palindrome or not.

Palindrome.vb

1. Imports System  
2. Module Palindrome  
3.     ' Define a reverse() function   
4.     Function reverse(ByVal num As Integer) As Integer  
5.         ' Define the local variable  
6.         Dim remain As Integer  
7.         Dim rev As Integer = 0  
8.         While (num > 0)  
9.             remain = num Mod 10  
10.             rev = rev * 10 + remain  
11.             num = num / 10  
12.         End While  
13.         Return rev  
14.     End Function  
15.     Sub Main()  
16.         ' Define the local variable as integer  
17.         Dim n, num2 As Integer  
18.         Console.WriteLine(" Enter a number")  
19.         n = Console.ReadLine() 'Accept the number  
20.         num2 = reverse(n) ' call a function  
21.         Console.WriteLine(" Reverse of {0} is {1}", n, num2)  
22.   
23.         If (n = reverse(n)) Then  
24.             Console.WriteLine(" Number is a Palindrome")  
25.         Else  
26.             Console.WriteLine(" Number is not a Palindrome")  
27.         End If  
28.         Console.WriteLine("Press any key to exit...")  
29.         Console.ReadKey()  
30.     End Sub  
31. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Recursive Function
When a function calls itself until the defined condition is satisfied, it is known as a recursive function. A
recursive function is useful for solving many mathematical tasks such as generating the Fibonacci series,
the factorial of a number, etc.

Let's create a program to calculate the factorial of a number using the recursive function.

Factorial_function.vb

1. Imports System  
2. Module Factorial_function  
3.     ' Create a Fact() function  
4.     Function Fact(ByVal num As Integer) As Integer  
5.         If (num = 0) Then  
6.             Return 0  
7.         ElseIf (num = 1) Then  
8.             Return 1  
9.         Else  
10.             Return num * Fact(num - 1)  
11.         End If  
12.     End Function  
13.     Sub Main()  
14.         ' Define the local variable as integer  
15.         Dim n, f As Integer  
16.         Console.WriteLine(" Enter the number you want to calculate factorial")  
17.         n = Console.ReadLine() 'Accept a number  
18.         f = Fact(n) 'call Fact() function  
19.         Console.WriteLine(" Factorial is : {0}", f)  
20.         Console.WriteLine(" Press any key to exit...")  
21.         Console.ReadKey()  
22.     End Sub  
23. End Module  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Output:

Passing Array as a Parameter


Let's create a program that parses an array as a pass parameters in a function.

Array_Parameter.vb

1. Imports System  
2. Module array_Parameter  
3.     Function AddPara(ByVal Arr As Integer(), ByVal size As Integer) As Double  
4.         'Declare a local variable.  
5.   
6.         Dim i As Integer  
7.         Dim avg As Double  
8.         Dim Sum As Integer = 0  
9.   
10.         For I = 0 To size - 1  
11.             Sum = Sum + Arr(i)  
12.         Next  
13.         avg = Sum / size  
14.         Return avg  
15.     End Function  
16.     Sub Main()  
17.         Dim arrays As Integer() = {50, 10, 20, 5, 4, 25}  
18.         Dim getAvg As Double  
19.         getAvg = AddPara(arrays, 6)  
20.         Console.WriteLine("Average sum of array element is {0}", getAvg)  
21.         Console.WriteLine(" Press any key to exit...")  
22.         Console.ReadKey()  
23.     End Sub  
24. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

VB.NET 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:

1. [Access_Specifier ] Sub Sub_name [ (parameterList) ]   
2. [ Block of Statement to be executed ]  
3. End Sub  

Where,

o 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.
o Sub_name: The Sub_name indicates the name of the Sub that should be unique.
o ParameterList: It defines the list of the parameters to send or retrieve data from a method.

The following are the different ways to define the types of Sub method.

1. Public Sub getDetails()  
2. ' Statement to be executed  
3. End Sub  
4.   
5. Private Sub GetData( ByVal username As String) As String  
6. ' Statement to be executed  
7. End Sub  
8.   
9. Public Function GetData1( ByRef username As String, ByRef userId As Integer)  
10. ' Statement to be executed  
11. End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Example: Write a simple program to pass the empty, a single or double parameter of Sub procedure in
the VB.NET

Sub_Program.vb

1. Module Sub_Program  
2.     Sub sample()  
3.         Console.WriteLine("Welcome to JavaTpoint")  
4.     End Sub  
5.   
6.     Sub circle(ByVal r As Integer)  
7.         Dim Area As Integer  
8.         Const PI = 3.14  
9.         Area = PI * r * r  
10.         Console.WriteLine(" Area Of circle is : {0}", Area)  
11.     End Sub  
12.   
13.     ' Create the SumOfTwo() Function and pass the parameters.  
14.     Sub SumOfTwo(ByVal n1 As Integer, ByVal n2 As Integer)  
15.         ' Define the local variable.  
16.         Dim sum As Integer = 0  
17.         sum = n1 + n2  
18.         Console.WriteLine(" Sum of two number is : {0}", sum)  
19.     End Sub  
20.   
21.     Sub SubtractionOfTwo(ByVal n1 As Integer, ByVal n2 As Integer)  
22.         ' Define the local variable.  
23.         Dim subtract As Integer  
24.         subtract = n1 - n2  
25.         Console.WriteLine(" Subtraction of two number is : {0}", subtract)  
26.     End Sub  
27.   
28.     Sub MultiplicationOfTwo(ByVal n1 As Integer, ByVal n2 As Integer)  
29.         ' Define the local variable.  
30.         Dim multiply As Integer  
31.         multiply = n1 * n2  
32.         Console.WriteLine(" Multiplication of two number is : {0}", multiply)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

33.     End Sub  
34.   
35.     Sub Main()  
36.         ' Define the local variable a, b and rad.  
37.         Dim a, b, rad As Integer  
38.         sample() ' call sample() procedure  
39.         Console.WriteLine(" Please enter the First Number : ")  
40.         a = Console.ReadLine()  
41.         Console.WriteLine(" Second Number is : ")  
42.         b = Console.ReadLine()  
43.   
44.         SumOfTwo(a, b) 'call SumOfTwo() Function  
45.         SubtractionOfTwo(a, b) 'call SubtractionOfTwo() Function  
46.         MultiplicationOfTwo(a, b) 'call MultiplicationOfTwo() Function  
47.   
48.         Console.WriteLine(" Enter the radius of circle : ")  
49.         rad = Console.ReadLine()  
50.         circle(rad)  
51.         Console.WriteLine(" Press any key to exit...")  
52.         Console.ReadKey()  
53.     End Sub  
54. End Module  

Output:

In the VB.NET programming language, we can pass parameters in two different ways:

o Passing parameter by Value


o Passing parameter by Reference
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
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:

1. Sub Sub_method( ByVal parameter_name As datatype )  
2. [ Statement to be executed]  
3. 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

1. Imports System  
2. Module Passing_value  
3.     Sub Main()  
4.         ' declaration of local variable  
5.         Dim num1, num2 As Integer  
6.         Console.WriteLine(" Enter the First number")  
7.         num1 = Console.ReadLine()  
8.         Console.WriteLine(" Enter the Second number")  
9.         num2 = Console.ReadLine()  
10.         Console.WriteLine(" Before swapping the value of 'num1' is {0}", num1)  
11.         Console.WriteLine(" Before swapping the value of 'num2' is {0}", num2)  
12.         Console.WriteLine()  
13.   
14.         'Call a function to pass the parameter for swapping the numbers.  
15.         swap_value(num1, num2)  
16.         Console.WriteLine(" After swapping the value of 'num1' is {0}", num1)  
17.         Console.WriteLine(" After swapping the value of 'num2' is {0}", num2)  
18.         Console.WriteLine(" Press any key to exit...")  
19.         Console.ReadKey()  
20.     End Sub  
21.   
22.     ' Create a swap_value() method  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

23.     Sub swap_value(ByVal a As Integer, ByVal b As Integer)  
24.         ' Declare a temp variable  
25.         Dim temp As Integer  
26.         temp = a ' save the value of a to temp  
27.         b = a   ' put the value of b into a  
28.         b = temp ' put the value of temp into b  
29.     End Sub  
30. End Module  

Output:

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:

1. Sub Sub_method( ByRef parameter_name, ByRef Parameter_name2 )  
2. [ Statement to be executed]  
3. 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

1. Imports System  
2. Module Passing_ByRef  
3.     Sub Main()  
4.         ' declaration of local variable  
5.         Dim num1, num2 As Integer  
6.         Console.WriteLine(" Enter the First number")  
7.         num1 = Console.ReadLine()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

8.         Console.WriteLine(" Enter the Second number")  
9.         num2 = Console.ReadLine()  
10.         Console.WriteLine(" Before swapping the value of 'num1' is {0}", num1)  
11.         Console.WriteLine(" Before swapping the value of 'num2' is {0}", num2)  
12.         Console.WriteLine()  
13.   
14.         'Call a function to pass the parameter for swapping the numbers.  
15.         swap_Ref(num1, num2)  
16.         Console.WriteLine(" After swapping the value of 'num1' is {0}", num1)  
17.         Console.WriteLine(" After swapping the value of 'num2' is {0}", num2)  
18.         Console.WriteLine(" Press any key to exit...")  
19.         Console.ReadKey()  
20.     End Sub  
21.   
22.     ' Create a swap_Ref() method  
23.     Sub swap_Ref(ByRef a As Integer, ByRef b As Integer)  
24.         ' Declare a temp variable  
25.         Dim temp As Integer  
26.         temp = a ' save the value of a to temp  
27.         a = b   ' put the value of b into a  
28.         b = temp ' put the value of temp into b  
29.     End Sub  
30. End Module  

Output:

VB.NET 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. Furthermore, we can say that it is like a
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
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

We can create a class using the Class keyword, followed by the class name. And the body of the class
ended with the statement End Class. Following is the general syntax for creating classes and objects in
the VB.NET programming language

1. [ Access_Specifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] Class ClassName  
2. ' Data Members or Variable Declaration  
3. ' Methods Name  
4. ' Statement to be executed  
5. End Class  

Where,

o 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).
o Shadows: It is an optional parameter. It represents the re-declaration of variables and hides an
identical element name or set of overloaded elements in a base class.
o 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.
o NotInheritable: It is also an optional parameter that representing the class not being used as a
base class.
o Partial: As the name defines, a Partial represents the partial definition of the class (optional).
o Implements: It is used to specify interfaces from which the class inherits (optional).

My_program.vb

1. Public Class My_program  
2. ' properties, method name, etc  
3. ' Statement to be executed  
4. 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

1. Dim Obj_Name As Class_Name = New Class_Name() ' Declaration of object  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

2. 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

1. Imports System  
2. Module My_program  
3.     Sub Main()  
4.         Dim rect As Rectangle = New Rectangle() 'create an object  
5.         Dim rect2 As Rectangle = New Rectangle() 'create an object  
6.         Dim area, para As Integer  
7.   
8.         'rect specification  
9.         rect.setLength = (5)  
10.         rect.setBreadth= (6)  
11.   
12.         'rect2 specification  
13.         rect2.setLength = (5)  
14.         rect2.setBreadth = (10)  
15.   
16.         'Area of rectangle   
17.         area = rect.length * rect.Breadth  
18.         'area = rect.GetArea()  
19.         Console.WriteLine(" Area of Rectangle is {0}", area)  
20.   
21.         'Parameter of rectangle   
22.         'para = rect.GetParameter()  
23.          para = 2 (rect2.length + rect.Breadth)  
24.         Console.WriteLine(" Parameter of Rectangle is {0}", para)  
25.         Console.WriteLine(" Press any key to exit...")  
26.         Console.ReadKey()  
27.     End Sub  
28.     Public Class Rectangle  
29.         Public length As Integer  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

30.         Public Breadth As Integer  
31.   
32.         Public Sub setLength(ByVal len As Integer)  
33.             length = len  
34.         End Sub  
35.   
36.         Public Sub setBreadth(ByVal bre As Integer)  
37.             Breadth = bre  
38.         End Sub  
39.         Public Function GetArea() As Integer  
40.             Return length * Breadth  
41.         End Function  
42.   
43.         Public Function GetParameter() As Integer  
44.             Return 2 * (length + Breadth)  
45.         End Function  
46.     End Class  
47. End Module  

Output:

Member Function
The member function of a class is used to define the structure of member inside the definition of the class.
It can be accessed by all defined objects of the class and operated on the data member. Furthermore,
member variables are the attributes of an object to be implemented to a member function. And we can
access member variables using the public member function.

Constructor and Destructor


In VB.NET, the constructor is a special method that is implemented when an object of a particular class is
created. Constructor is also useful for creating and setting default values for a new object of a data
member.

When we create a class without defining a constructor, the compiler automatically creates a default
constructor. In this way, there is a constructor that is always available in every class. Furthermore, we can
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
create more than one constructor in a class with the use of New keyword but with the different
parameters, and it does not return anything.

Default Constructor: In VB.NET, when we create a constructor without defining an argument, it is called a
default constructor.

VB.NET Default Constructor Syntax

The following is the syntax for creating a constructor using the New keyword in VB.NET.

1. Public Class MyClass  
2. ' Creates a Constructor using the New         
3. Public Sub New()  
4.     'Statement to be executed  
5.        End Sub  
6. End Class   

Let's create a program to define the default constructor in a VB.NET programming language.

Default_Const.vb

1. Imports System  
2. Module Default_Const  
3.     Class Tutor  
4.         Public name As String  
5.         Public topic As String  
6.         ' Create a default constructor  
7.         Public Sub New()  
8.             name = "JavaTpoint"  
9.             topic = "VB.NET Tutorial"  
10.         End Sub  
11.     End Class  
12.     Sub Main()  
13.         ' The constructor will automatically call when the instance of the class is created  
14.         Dim tutor As Tutor = New Tutor() ' Create an object as a tutor  
15.         Console.WriteLine(" Your Site Name is : {0}", tutor.name)  
16.         Console.WriteLine(" Your Topic Name is : {0}", tutor.topic)  
17.         Console.WriteLine(" Press any key to exit...")  
18.         Console.ReadKey()  
19.     End Sub  
20. End Module  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Output:

In the above example, we created a class 'Tutor' and defined a default constructor method


with New() keyword without passing any arguments. When the object (tutor) is created, the default
constructor is called into the class.

Parameterized Constructor

In VB.NET, when we pass one or more arguments to a constructor, the constructor is known as a
parameterized constructor. And the object of the class should be initialized with arguments when it is
created.

Let's create a program to use the parameterized constructor to pass the argument in a class.

Para_Const.vb

1. Imports System  
2. Module Para_Const  
3.     Class Tutor  
4.         Public name As String  
5.         Public topic As String  
6.         ' Create a parameterized constructor to pass parameter  
7.         Public Sub New(ByVal a As String, ByVal b As String)  
8.             name = a  
9.             topic = b  
10.             Console.WriteLine(" We are using a parameterized constructor to pass the parameter")  
11.         End Sub  
12.     End Class  
13.     Sub Main()  
14.         ' The constructor will automatically call when the instance of the class is created  
15.         Dim tutor As Tutor = New Tutor("JavaTpoint", "VB.NET Constructor")  
16.         Console.WriteLine(" Your Site Name is : {0}", tutor.name)  
17.         Console.WriteLine(" Your Topic Name is : {0}", tutor.topic)  
18.         Console.WriteLine(" Press any key to exit...")  
19.         Console.ReadKey()  
20.     End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

21. End Module  

Output:

VB.NET Destructor
In VB.NET, Destructor is a special function that is used to destroy a class object when the object of the class
goes out of scope. It can be represented as the Finalize() method and does not accept any parameter nor
return any value. Furthermore, it can be called automatically when a class object is not needed.

VB.NET Destructor Syntax

Destructor using the Finalize() method in VB.NET.

1. Class My_Destructor  
2.  ' define the destructor   
3.     Protected Overrides Sub Finalize()  
4. ' Statement or code to be executed   
5. End Sub  
6. End Class  

Let's create a program to use the Finalize() method in VB.NET Destructor.

Destruct.vb

1. Imports System  
2. Module Destruct  
3.     Class Get_Destroy  
4.         Public Sub New()  
5.             Console.WriteLine(" An Object of the class is being created")  
6.         End Sub  
7.         ' Use Finalize() method of Destructor  
8.         Protected Overrides Sub Finalize()  
9.             Console.WriteLine(" An Object of the class is being destroyed")  
10.             Console.WriteLine(" Press any key to exit")  
11.         End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

12.     End Class  
13.   
14.     Sub Main()  
15.         Get_Details() ' After invoking the Get_Details() method, garbage collector is called automatically  
16.         GC.Collect()  
17.         Console.ReadKey()  
18.         End Sub  
19.     Public Sub Get_Details()  
20.         Dim dest As Get_Destroy = New Get_Destroy()  
21.     End Sub  
22. End Module  

Output:

Constructor Overloading
In VB.NET, the overloading of constructors is a concept in which we can overload constructors by defining
more than one constructor with the same name but with different parameter lists to perform different
tasks.

Let's create a program to use the Constructor Overloading in a class.

Const_Over.vb

1. Imports System  
2. Module Const_Over  
3.     Class Details  
4.         Public name As String  
5.         Public course As String  
6.         ' Define Default Constructor  
7.         Public Sub New()  
8.             name = "Prince"  
9.             course = "Coputer Science"  
10.             Console.WriteLine(" Uses of Overloading Constructor")  
11.         End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

12.         ' Create a parametrized constructor  
13.         Public Sub New(ByVal a As String, ByVal b As String)  
14.             name = a  
15.             course = b  
16.         End Sub  
17.     End Class  
18.     Sub Main()  
19.         ' Called default constructor  
20.         Dim det As Details = New Details()  
21.         ' Called the parametrized constructor   
22.         Dim det1 As Details = New Details("Peter", "Knowledge of Data Mining")  
23.         Console.WriteLine(" Your Details are: Name : {0} and Course : {1}", det.name, det.course)  
24.         Console.WriteLine(" Your Overloaded Details are: Name : {0} and Course :{1}", det1.name, det1.course)  
25.         Console.WriteLine(" Press any key to exit...")  
26.         Console.ReadKey()  
27.     End Sub  
28. End Module  

Output:

Inheritance
In VB.NET, Inheritance is the process of creating a new class by inheriting properties and functions from
the old class and extending the functionality of the existing class. It also provides a reusable and faster
implementation time of the code. When we create a derived or inherited class, inheritance allows us to
inherit all the properties of the existing class. The old class is known as the base class, and the inherited
class is known as the derived class.

Inheritance Syntax

The following is the syntax of Inheritance in VB.NET.

1. <access_modifier> Class <Name_of_baseClass>  
2. ' Implementation of base class  
3. End Class  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

4. <access_modifier> Class <Name_of_derivedClass>  
5. Inherits Name_of_baseClass  
6. ' Implementation of derived class  
7. End Class  

Let's create a program to understand the concept of Inheritance in VB.NET

Simple_Inherit.vb

1. Imports System  
2. Module Simple_Inherit  
3.     Public Class Vehicle  
4.         Public Sub speed()  
5.             Console.WriteLine(" 4 Wheeler cars are more luxurious than 2 Wheeler")  
6.         End Sub  
7.   
8.         Public Overridable Sub perform()  
9.             Console.WriteLine(" Both Vehicles are good, but in a narrow lane, two-wheeler are more comfortabl
e than 4-Wheeler")  
10.         End Sub  
11.     End Class  
12.   
13.     Class Bike  
14.         Inherits Vehicle  
15.         Public Overrides Sub perform()  
16.             Console.WriteLine(" Two-wheeler are lesser weight as compared to 4 wheeler")  
17.         End Sub  
18.     End Class  
19.     Class Car  
20.         Inherits Vehicle  
21.         Public Overrides Sub perform()  
22.             Console.WriteLine(" It is 4 wheelar car")  
23.         End Sub  
24.     End Class  
25.   
26.     Sub Main()  
27.         Dim vehicle As Vehicle = New Vehicle()  
28.         Dim bike As Bike = New Bike()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

29.         Dim car As Car = New Car()  
30.         vehicle = bike  
31.         vehicle.perform()  
32.         vehicle = car  
33.         vehicle.perform()  
34.         Console.WriteLine(" Press any ley to exit...")  
35.         Console.ReadKey()  
36.     End Sub  
37. End Module  

Output:

Let's create a program of inheritance using the MyBase in VB.NET.

Inherit_class.vb

1. Module Inherit_class  
2.     Class Circle   'base class  
3.         Protected radius As Integer  
4.         Public Const PI As Double = 3.14  
5.         Public Sub New(ByVal r As Integer)  
6.             radius = r  
7.         End Sub  
8.         Public Function GetAreaCircle() As Double  
9.             Return (PI * radius * radius)  
10.         End Function  
11.         Public Overridable Sub Show()  
12.             Console.WriteLine(" Radius of circle : {0}", radius)  
13.             Console.WriteLine(" Area of circle is {0}", GetAreaCircle())  
14.         End Sub  
15.     End Class  
16.   
17.     'Derived Class  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

18.     Class MyDeriveClass : Inherits Circle  
19.         Private dimen As Double  
20.         Public Sub New(ByVal r As Integer)  
21.             MyBase.New(r)  
22.         End Sub  
23.         Public Function Getdimen() As Double  
24.             Dim dimen As Double  
25.             dimen = GetArea() * 50  
26.             Return dimen  
27.         End Function  
28.         Public Overrides Sub Show()  
29.             MyBase.Show()  
30.             Console.WriteLine("Total Cost: {0}", Getdimen())  
31.         End Sub  
32.     End Class  
33.   
34.     Class Circle_Class  
35.         Shared Sub Main()  
36.             Dim c As MyDeriveClass = New MyDeriveClass(5)  
37.             c.Show()  
38.             Console.WriteLine("Press any key to exit")  
39.             Console.ReadKey()  
40.         End Sub  
41.     End Class  
42. End Module  

Output:

Multi-Level Inheritance
VB.NET only supports single inheritance that means a class can be inherited from the base class. However,
VB.NET uses hierarchical inheritance to extend one class to another class, which is called  Multi-Level
Inheritance. For example, Class C extends Class B, and Class B extends Class A, Class C will inherit the
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
member of both class B and Class A. The process of extending one class to another is known as multilevel
inheritance.

1. Public Class A  
2.      ' implementation of code  
3. End Class  
4.   
5. Public Class B  
6.       Inherits A  
7.       ' Implementation of Code  
8. End Class  
9.   
10. Public Class C  
11.        Inherits A  
12.        ' Implementation of code  
13. End Class  

Let's create a program to understand the concept of Multi-Level Inheritance in VB.NET

Multi_inherit1.vb

1. Module Multi_inherit1  
2.     Public Class A  
3.         Public SName As String  
4.         Public Sub Display()  
5.             Console.WriteLine(" Name of Student : {0}", SName)  
6.         End Sub  
7.     End Class  
8.     Public Class B  
9.         Inherits A  
10.         Public place As String  
11.         Public Sub GetPlace()  
12.             Console.WriteLine(" Address : {0}", place)  
13.         End Sub  
14.     End Class  
15.   
16.     Public Class C  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

17.         Inherits B  
18.         Public rollno As Integer  
19.         Public Sub GetRollno()  
20.             Console.WriteLine(" Student Roll no. {0}", rollno)  
21.         End Sub  
22.     End Class  
23.   
24.     Class Profile  
25.         Public Sub Main(ByVal args As String())  
26.             Dim c As C = New C()  
27.             c.SName = "Donald Trump"  
28.             c.place = "USA"  
29.             c.rollno = 102  
30.             c.Display()  
31.             c.GetPlace()  
32.             c.GetRollno()  
33.             Console.WriteLine(" Press any key to exit")  
34.             Console.ReadKey()  
35.         End Sub  
36.     End Class  
37. End Module  

Output:

Interface
In VB.NET, the interface is similar to a class for inheriting all properties, methods, and events that a class or
structure can implement. Using the interface in VB.NET, we can use multiple inheritances of classes. It uses
the Implements keyword to implement the interfaces, and the Interface keyword is used to create the
interface. All interfaces in VB.NET starts with i.

The Syntax for implementing an interface in a class.

1. Class MyClass  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

2.     Inherits IClass  
3.     Private Sub FetchDetails() Implements IClass.FetchDetails  
4.     ' Method Implementation   
5.     End Sub  
6. End Class  

In the above snippets, we inherited an interface (IClass) in the Class MyClass that implemented to the
interface method defined in a class.

Let's create and implement an instance using a class in VB.NET.

Get_Interface.vb

1. Module Get_Interface  
2.     Interface IStudent  
3.         Sub Details(ByVal y As String)  
4.     End Interface  
5.     Class Student  
6.         Implements IStudent  
7.         Public Sub Details(ByVal a As String) Implements IStudent.Details  
8.             '       Throw New NotImplementedException()  
9.             Console.WriteLine(" Name of Student: {0}", a)  
10.         End Sub  
11.     End Class  
12.   
13.     Class Student1  
14.         Implements IStudent  
15.         Public Sub Details(ByVal a As String) Implements IStudent.Details  
16.             'Throw New NotImplementedException()  
17.             Console.WriteLine(" Course: {0}", a)  
18.         End Sub  
19.     End Class  
20.     Sub Main(ByVal args As String())  
21.         Dim stud As IStudent = New Student()  
22.         stud.Details(" James Watt")  
23.         Dim stud1 As IStudent = New Student1()  
24.         stud1.Details("Computer Science")  
25.         Console.WriteLine(" Press any key to exit...")  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

26.         Console.ReadKey()  
27.     End Sub  
28. End Module   

Output:

VB.NET Multithreading
What is VB.NET Thread?
When two or more processes execute simultaneously in a program, the process is known as
multithreading. And the execution of each process is known as the thread. A single thread is used to
execute a single logic or task in an application. By default, each application has one or more threads to
execute each process, and that thread is known as the main thread.

To create and access a new thread in the Thread class, we need to import


the System.Threading namespace. When the execution of a program begins in VB.NET, the Main thread is
automatically called to handle the program logic. And if we create another thread to execute the process in
Thread class, the new thread will become the child thread for the main thread.

Create a new Thread


In VB.NET, we can create a thread by extending the Thread class and pass the ThreadStart delegate as an
argument to the Thread constructor. A ThreadStart() is a method executed by the new thread. We need to
call the Start() method to start the execution of the new thread because it is initially in the unstart state.
And the PrintInfo parameter contains an executable statement that is executed when creating a new
thread.

1. ' Create a new thread  
2. Dim th As Thread = New Thread( New ThreadStart(PrintInfo)  
3. ' Start the execution of newly thread  
4. th.Start()    

Let's write a program to create and access the thread in Thread class.

create_Thread.vb
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

1. Imports System.Threading 'Imports the System.Threading namespace.   
2. Module create_Thread  
3.     Sub Main(ByVal args As String())  
4.         ' create a new thread   
5.         Dim th As Thread = New Thread(New ThreadStart(AddressOf PrintInfo))  
6.         ' start the newly created thread  
7.         th.Start()  
8.         Console.WriteLine(" It is a Main Thread")  
9.     End Sub  
10.     Private Sub PrintInfo()  
11.         For j As Integer = 1 To 5  
12.             Console.WriteLine(" value of j is {0}", j)  
13.         Next j  
14.         Console.WriteLine(" It is a child thread")  
15.         Console.WriteLine(" Press any key to exit...")  
16.         Console.ReadKey()  
17.     End Sub  
18. End Module  

Output:

In the above program, the main and child threads begin their execution simultaneously. The execution of
the main thread is stopped after completing its function, but the child thread will continue to execute until
its task is finished.

VB.NET Thread Methods


The following are the most commonly used methods of Thread class.

Method Description

Abort() As the name defines, it is used to terminate the execution of a thread.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

AllocateDataSlot() It is used to create a slot for unnamed data on all threads.

AllocateNamedDatsSlot() It is used to create a slot for defined data on all threads.

Equals() It is used to check whether the current and defined thread object are
equal.

Interrupt() It is used to interrupt a thread from the Wait, sleep, and join thread state.

Join() It is a synchronization method that stops the calling thread until the
execution thread completes.

Resume() As the name suggests, a Resume() method is used to resume a thread


that has been suspended.

Sleep() It is used to suspend the currently executing thread for a specified time.

Start() It is used to start the execution of thread or change the state of an


ongoing instance.

Suspend() It is used to stop the currently executing thread.

VB.NET Thread Life Cycle


In VB.NET Multithreading, each thread has a life cycle that starts when a new object is created using the
Thread Class. Once the task defined by the thread class is complete, the life cycle of a thread will get the
end.

There are some states of thread cycle in VB.NET programming.

State Description

Unstarted When we create a new thread, it is initially in an unstarted state.

Runnable When we call a Start() method to prepare a thread for running, the runnable situation
occurs.

Running A Running state represents that the current thread is running.

Not It indicates that the thread is not in a runnable state, which means that the thread in
Runnable sleep() or wait() or suspend() or is blocked by the I/O operation.

Dead If the thread is in a dead state, either the thread has been completed its work or
aborted.

Let's create a program to manage a thread by using various methods of Thread Class.

Thread_cycle.vb

1. Imports System.Threading  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

2. Module Thread_cycle  
3.     Sub Main(ByVal args As String())  
4.         Dim s As Stopwatch = New Stopwatch()  
5.         s.Start()  
6.         Dim t As Thread = New Thread(New ThreadStart(AddressOf PrintInfo))  
7.         t.Start()  
8.         ' Halt another thread execution until the thread execution completed  
9.         t.Join()  
10.         s.[Stop]()  
11.         Dim t1 As TimeSpan = s.Elapsed  
12.         Dim ft As String = String.Format("{0}: {1} : {2}", t1.Hours, t1.Minutes, t1.Seconds)  
13.         Console.WriteLine(" Total Elapsed Time : {0}", ft)  
14.         Console.WriteLine("Completion of Thread Execution ")  
15.         Console.WriteLine("Press any key to exit...")  
16.         Console.ReadKey()  
17.     End Sub  
18.     Private Sub PrintInfo()  
19.         For j As Integer = 1 To 6  
20.             Console.WriteLine(" Halt Thread for {0} Second", 5)  
21.             ' It pause thread for 5 Seconds  
22.             Thread.Sleep(5000)  
23.             Console.WriteLine(" Value of i {0}", j)  
24.         Next  
25.     End Sub  
26. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

In the above example, we used a different method of the Thread class such as the Start() method to start
execution of the thread, the Join() method is used to stop the execution of the thread until the execution
of the thread was completed. The Sleep() method is used to pause the execution of threads for 5 seconds.

Multithreading
When two or more processes are executed in a program to simultaneously perform multiple tasks, the
process is known as multithreading.

When we execute an application, the Main thread will automatically be called to execute the programming
logic synchronously, which means it executes one process after another. In this way, the second process
has to wait until the first process is completed, and it takes time. To overcome that situation, VB.NET
introduces a new concept Multithreading to execute multiple tasks at the same time by creating multiple
threads in a program.

Let's write a program of multiple threads to execute the multiple tasks at the same time in the VB.NET
application.

Multi_thread.vb

1.  Imports System.Threading  
2. Module Multi_thread  
3.     Sub Main(ByVal arg As String())  
4.         Dim th As Thread = New Thread(New ThreadStart(AddressOf PrintInfo))  
5.         Dim th2 As Thread = New Thread(New ThreadStart(AddressOf PrintInfo2))  
6.         th.Start()  
7.         th2.Start()  
8.         Console.ReadKey()  
9.     End Sub  
10.     Private Sub PrintInfo()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

11.         For j As Integer = 1 To 5  
12.             Console.WriteLine(" value of j is {0}", j)  
13.             Thread.Sleep(1000)  
14.         Next  
15.         Console.WriteLine(" Completion of First Thread")  
16.     End Sub  
17.     Private Sub PrintInfo2()  
18.         For k As Integer = 1 To 5  
19.             Console.WriteLine(" value of k is {0}", k)  
20.         Next  
21.         Console.WriteLine(" Completion of First Thread")  
22.     End Sub  
23. End Module  

Output:

In the above example, we have created two threads (th, th2) to execute
the PrintInfo and PrintInfo2 method at the same time. And when execution starts, both threads execute
simultaneously. But the first statement of the PrintInfo method is executed, and then it waits for the next
statement until the PrintInfo2 method is completed in the program.

VB.NET Exception Handling


What is an Exception?
An exception is an unwanted error that occurs during the execution of a program and can be a system
exception or application exception. Exceptions are nothing but some abnormal and typically an event or
condition that arises during the execution, which may interrupt the normal flow of the program.

An exception can occur due to different reasons, including the following:


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

o A user has entered incorrect data or performs a division operator, such as an attempt to divide by
zero.
o A connection has been lost in the middle of communication, or system memory has run out.

Exception Handling
When an error occurred during the execution of a program, the exception provides a way to transfer
control from one part of the program to another using exception handling to handle the
error. VB.NET exception has four built-in keywords such as Try, Catch, Finally, and Throw to handle and
move controls from one part of the program to another.

Keyword Description

Try A try block is used to monitor a particular exception that may throw an exception within
the application. And to handle these exceptions, it always follows one or more catch
blocks.

Catch It is a block of code that catches an exception with an exception handler at the place in a
program where the problem arises.

Finally It is used to execute a set of statements in a program, whether an exception has occurred.

Throw As the name suggests, a throw handler is used to throw an exception after the occurrence
of a problem.

Exception Classes in VB.NET


In VB.net, there are various types of exceptions represented by classes. And these exception classes
originate from their parent's class 'System.Exception'.

The following are the two exception classes used primarily in VB.NET.

1. System.SystemException
2. System.ApplicationException

System.SystemException: It is a base class that includes all predefined exception classes, and some
system-generated exception classes that have been generated during a run time such
as DivideByZeroException, IndexOutOfRangeException, StackOverflowExpression, and so on.

System.ApplicationException: It is an exception class that throws an exception defined within the


application by the programmer or developer. Furthermore, we can say that it is a user-defined exception
that inherits from System.ApplicationException class.

Syntax of exception handler block

1. Try  
2.     ' code or statement to be executed  
3.     [ Exit Try block]  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

4. ' catch statement followed by Try block  
5. Catch [ Exception name] As [ Exception Type]   
6. [Catch1 Statements] Catch [Exception name] As [Exception Type]  
7. [ Exit Try ]  
8.  [ Finally  
9.     [ Finally Statements ] ]  
10. End Try  

In the above syntax, the Try/Catch block is always surrounded by a code that can throw an exception. And
the code is known as a protected code. Furthermore, we can also use multiple catch statements to catch
various types of exceptions in a program, as shown in the syntax.

Example to Exception Handle


Let's create a program to handle an exception using the Try, Catch, and Finally keywords for Dividing a
number by zero in VB.NET programming.

TryException.vb

1. Module TryException  
2.     Sub divExcept(ByVal a As Integer, ByVal b As Integer)  
3.         Dim res As Integer  
4.         Try  
5.             res = a \ b  
6.             ' Catch block followed by Try block  
7.         Catch ex As DivideByZeroException  
8.             Console.WriteLine(" These exceptions were found in the program {0}", ex)  
9.             ' Finally block will be executed whether there is an exception or not.  
10.         Finally  
11.             Console.WriteLine(" Division result is {0}", res)  
12.         End Try  
13.     End Sub  
14.     Sub Main()  
15.         divExcept(5, 0) ' pass the parameters value  
16.         Console.WriteLine(" Press any key to exit...")  
17.         Console.ReadKey()  
18.     End Sub  
19. End Module  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Output:

Creating User-Defined Exceptions


It allows us to create custom exceptions derived from the ApplicationException class.

Let's create a program to understand the uses of User-Defined Exceptions in VB.NET Exception Handling.

User_Exception.vb

1. Module User_Exception  
2.     Public Class StudentIsZeroException : Inherits Exception  
3.   
4.         Public Sub New(ByVal stdetails As String)  
5.             MyBase.New(stdetails)  
6.         End Sub  
7.     End Class  
8.     Public Class StudentManagement  
9.         Dim stud As Integer = 0  
10.         Sub ShowDetail()  
11.             If (stud = 0) Then  
12.                 Throw (New StudentIsZeroException(" Student roll no 'zero' does not exist"))  
13.             Else  
14.                 Console.WriteLine("  Student is {0}", stud)  
15.             End If  
16.         End Sub  
17.     End Class  
18.     Sub Main()  
19.         Dim stdmg As StudentManagement = New StudentManagement()  
20.         Try  
21.             stdmg.ShowDetail()  
22.         Catch ex As StudentIsZeroException  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

23.             Console.WriteLine(" StudentIsZeroException {0}", ex.message)  
24.         End Try  
25.         Console.ReadKey()  
26.     End Sub  
27. End Module  

Output:

Using Try-Catch Statement


Lets' create a program using the Try-Catch statement in VB.NET to handle the exceptions.

Try_catch.vb

1. Imports System  
2. Module Try_catch  
3.     Sub Main(ByVal args As String())  
4.         Dim strName As String = Nothing  
5.         Try  
6.             If strName.Length > 0 Then ' it thows and exception  
7.                 Console.WriteLine(" Name of String is {0}", strName)  
8.             End If  
9.         Catch ex As Exception  ' it cacthes an exception  
10.             Console.WriteLine(" Catch exception in a proram {0}", ex.Message)  
11.         End Try  
12.         Console.WriteLine(" Press any key to exit...")  
13.         Console.ReadKey()  
14.     End Sub  
15. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Throwing Objects
In VB.NET exception handling, we can throw an object exception directly or indirectly derived from
the System.Exception class. To throw an object using the throw statement in a catch block, such as:

1. Throw [ expression ]  

Let's create a program to throw an object in VB.NET exception.

throwexcept.vb

1. Imports System  
2. Module thowexcept  
3.     Sub Main()  
4.         Try  
5.             Throw New ApplicationException("It will throw a custom object exception")  
6.         Catch ex As Exception  
7.             Console.WriteLine(" Custom Exception is: {0}", ex.Message)  
8.         Finally  
9.             Console.WriteLine("Finally block statement executes whether there is an exception or not.")  
10.         End Try  
11.         Console.WriteLine(" Press any key to exit")  
12.         Console.ReadKey()  
13.     End Sub  
14. End Module  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Output:

VB.NET File Handling


A file is a collection of data stored in computer memory with a specific name and a defined folder path.
The term File Handling in VB.NET is used to perform various operations like create a file, read a file, write
to the file, closing the file, and more. Furthermore, when a file is opened for reading and writing,
a stream is created.

A stream is a sequence of bytes that passes data to a file to read or write. In VB.NET file handling, there are
two types of stream such as Input Stream or Read Stream and Output Stream or Write Stream.

VB.NET I/O Classes


In VB.NET, we use the System.IO namespace, that has different classes to perform various input and
output operations with files, such as the FileStream class used to perform any operation like opening a
file, closing a file, deleting a files, reading from or writing to a file, etc.

The following table shows the I/O classes that are commonly used in VB.NET programming.

I/O Class Description

File It is used to perform some changes in files.

FileInfo It is used to perform any operation on files.

FileStream It is used to apply read or write operations on any location of a file.

BinaryReader As the name represents, a Binary reader is used to read primitive data in a binary
stream.

BinaryWriter It is used to write the data in binary format.

Directory It is used to perform some changes or manipulating a directory structure.

DriveInfo It helps to provide the necessary information for the drive.

BuffredStream It is a temporary storage area for the collection of steam bytes.

MemoryStream It is used to access stored streaming data in memory.

StreamReader A StreamReader property is used to read characters from the stream byte.

Path It is used to perform operations on the path of a file.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

StreamWriter A StreamWriter is used to write characters to a stream.

DirectoryInfo It is used to perform an operation on the directory.

StringReader It is used to read string from a string buffer.

FileStream Class
The FileStream class is provided by the System.IO namespace to read, write, close or create files in the file
handling.

Syntax:

1. Dim Obj_name As FileStream = New FileSteam("file_name", FileMode, FileAccess, FileShare)  

For example, we need to create a FileStream Object FS to read a file with named myfile.txt.

1. Dim FS As FileStream = New FileStream("myFile.txt", FileMode.Open, FileAccess.ReadWrite)  

The following table is the description of FilesStream Class.

Parameter Description

FileMode The FileMode represents the various method for opening or creating a file. Following
are the member of FileMode-
Append: It is used to open an existing file and put the cursor at the end of the file. And
if the file is not existing, it creates a file.
Create: As the name defines, a create is uses to create a new file.
CreateNew: It specifies the OS to create a new file.
Open: It is used to open an existing file.
OpenOrCreate: It is used to open an existing file, and if the file is not existing, it creates
a new file.
Truncate: It is used to open an existing file for shrinking its original size to zero bytes.

FileAccess It is used to perform any operation such as Read, ReadWrite, Delete and Write, etc.

FileShare A FileShare has the following members


Read: It permits to open a file for reading
Write: It permits you to open a file for writing.
None: It is used to reject the sharing of the current file.

Obj_name It represents the object name of the file.

Let's create a program to understand the concept of FileStream in VB.NET program.

File_Prog.vb
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

1. Imports System.IO  
2. Module File_Prog  
3.     Sub Main()  
4. ' Create an object FS for the FileStream class along with the name of the text file to perform operation like 
create, read or write.  
5.         Dim FS As FileStream = New FileStream("myFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)  
6.         Dim c As Integer  
7.         ' use for loop to read character  
8.         For c = 0 To 21  
9.             FS.WriteByte(CByte(c))  'write byte to the file  
10.         Next c  
11.         FS.Position = 0  
12.         Console.WriteLine("Bytes are:")  
13.         For c = 0 To 21  
14.         Console.WriteLine("{0} ", FS.ReadByte()) ' ReadByte() to read byte form the file.  
15.         Next c  
16.         FS.Close()  'Close the file  
17.         Console.WriteLine(" Press any key to exit...")  
18.         Console.ReadKey()  
19.     End Sub  
20. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

VB.NET has some advanced concepts of file operation.


1. StreamReader and StreamWriter

The StreamReader class is used to read a text from a text file, and the StreamWrite file is used to write a
text to a specified text file. These Stream classes are inherited from the Abstract base class stream, which
represents a reader to read a series of characters, and a writer can write a series of characters.

Example of StreamReader Class

Let's create the following example to understand the concept of StreamReader to read a text file named
Myfile.txt, as shown below.

Myfile.txt

1. What is an Exception?  
2. An exception is an unwanted error that occurs during the execution of a program and can be a system exc
eption or application exception.  

StReader.vb

1. Imports System.IO  
2. Module StReader  
3.     Sub Main()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

4.         ' Create St as an object of StreamReader Class  
5.         Dim St As StreamReader = New StreamReader("C:/Users/AMIT YADAV/Desktop/Myfile.txt")  
6.         Dim ln As String  
7.         ' It reads and prints the content from Myfile.txt  
8.         ln = St.ReadLine()  
9.         While (ln <> Nothing)  
10.             Console.WriteLine(ln)  
11.             ln = St.ReadLine()  
12.         End While  
13.         St.Close()  
14.         Console.ReadKey()  
15.     End Sub  
16. End Module  

Output:

Example of StreamWriter Class

Let's create the following example to understand the concept of StreamWriter to write a text into a file
Mytext.txt, as shown below.

StWriter.vb

1. Imports System.IO  
2. Module StWriter  
3.     Sub Main()  
4.         Dim ln As String  
5.         ' Create a path for Mytext.txt file to insert the below data.   
6.         Dim St As StreamWriter = New StreamWriter("C:/Users/AMIT YADAV/Desktop/Mytext.txt")  
7.         St.WriteLine(" Welcome To JavaTpoint")  
8.         St.WriteLine(" VB.NET is the Programming language")  
9.         St.WriteLine(" Learn VB.NET File Handling")  
10.         St.Close()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

11.   
12.         ' Read and print the data from the specified file.  
13.         Dim sw As StreamReader = New StreamReader("C:/Users/AMIT YADAV/Desktop/Mytext.txt")  
14.         ln = sw.ReadLine()  
15.         While (ln <> Nothing)  
16.             Console.WriteLine(ln)  
17.             ln = sw.ReadLine()  
18.         End While  
19.         sw.Close()  
20.         Console.WriteLine("Press any key to exit...")  
21.         Console.ReadKey()  
22.     End Sub  
23. End Module  

Output:

Further, we can also check if the file "Mytext.txt" is created on the defined route "C:/Users/AMIT
YADAV/Desktop/Mytext.txt" or not. And when we follow the defined path, it shows the following
content in Mytext file.

2. BinaryReader and BinaryWriter Classes

The BinaryReader and BinaryWriter classes are used with binary streams. Binary data is read and write using
its internal binary format, and these binary data are not human readable. The BinaryReader class can be
used to read binary data from a file, and the BinaryWriter file is used to write text to a specified binary file.

Example of BinaryWriter Class


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Let's create the following example to understand the concept of StreamWriter to write a text into a file
Mytext.txt, as shown below.

BinWriter.vb

1. Imports System.IO  
2. Module BinWriter  
3.     Sub Main()  
4.         Dim FS As FileStream = New FileStream("C:\Users\AMIT YADAV\Desktop\Myfolder\binary.txt", FileMo
de.OpenOrCreate, FileAccess.Write)  
5.         Dim binWriter As New BinaryWriter(FS)  
6.         Dim name As String = "Welcome to JavaTpoint"  
7.         Dim db As Double = 1010  
8.         Dim age As Integer = 10111  
9.         binWriter.Write(name)  
10.         binWriter.Write(db)  
11.         binWriter.Write(age)  
12.         binWriter.Close()  
13.         FS.Close()  
14.         Console.WriteLine(" Press any key to exit...")  
15.         Console.ReadKey()  
16.     End Sub  
17. End Module  

Output:

Example of BinaryReader Class

Let's create the following example to understand the concept of BinaryReader to read the text into a file
Mytext.txt.

BinReader.vb

1. Imports System.IO  
2. Module BinReader  
3.     Sub Main()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

4.         Dim FS As FileStream = New FileStream("C:\Users\AMIT YADAV\Desktop\Myfolder\binary.txt", FileMo
de.Open, FileAccess.Read)  
5.         Dim binReader As New BinaryReader(FS)  
6.         Dim a As Integer = binReader.ReadInt32()  
7.         Dim c As Char = binReader.ReadChar()  
8.         Dim f As Single = binReader.ReadSingle()  
9.         Console.WriteLine("Integer is {0}", a)  
10.         Console.WriteLine("Char data is {0}", c)  
11.         Console.WriteLine(" Float data is {0}", f)  
12.         binReader.Close()  
13.         FS.Close()  
14.         Console.WriteLine(" Press any key to exit...")  
15.         Console.ReadKey()  
16.     End Sub  
17. End Module  

Output:

3. FileInfo Class

The FileInfo class is used to get file properties such as file creation, copying, moving, name, and size. It
also helps to create a FileStream object, and the FileInfo class is derived from the FileSystemInfo class.

Let's create an example to understand the concept of the FileInfo class in VB.NET.

GetFilename.vb

1. Imports System.IO  
2. Module GetFilename  
3.     Sub Main()  
4.         Dim mk As DirectoryInfo = New DirectoryInfo("C:\Users\AMIT YADAV\Desktop\Myfolder")  
5.         Dim fl As FileInfo() = mk.GetFiles()  
6.         Dim f As FileInfo  
7.         For Each f In fl  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

8.             Console.WriteLine(" Name of File: {0} Size: {1} Creation time: {2} Extension of file is :{3}", f.Name, f.Le
ngth, f.CreationTime, f.Extension)  
9.         Next f  
10.         Console.WriteLine("Press any key to exit...")  
11.         Console.ReadKey()  
12.     End Sub  
13. End Module  

Output:

VB.NET Date & Time


In VB.NET, we use the Date and Time function to perform various operations related to date and time.
Sometimes we need to display the date and time in our application or web application, such as when the
last post edited, upgradation of new software version or patch-up details, etc.

In DateTime class, Date datatype stores date values, time values or date, and time values. Furthermore, to
perform the date and time function, we need to import the System.DateTime class. The default value of
DateTime is between 00:00:00 midnight, Jan 1, 0001 to 11:59:59 P.M., Dec 31, 9999 A.D.

Properties and method of DateTime


Date: It is used to return the date component of the DateTime Object.

Day: It is used to return the day of the month represented by the DateTime object.

DayOfWeek: It is used to return a particular day of the week represented by the DateTime object.

Minute: The Minute property is used to return the minute component by the DateTime object.

DateOfYear: It is used to return a day of the year represented by the DateTime object.

Hour: It is used to return the hour of the component of the date represented by the DateTime object.

Now: It is used to return the current date and time of the local system.

Month: The Month property is used to return the month name of the Datetime object.

Second: It is used to return the second of the DateTime object.

Ticks: It is used to return the number of ticks that refer to the DateTime object.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Today: It is used to return the current date of the system.

Year: It is used to return the year of the date represented by the DateTime object.

TimeOfDay: It is used to return the time of the day represented by the DateTime object.

Methods
The following are the most commonly used methods of the DateTime.

DaysInMonth: The DaysInMonth method is used to return the total number of days in the specified
month of the year.

Add: It is used to return a new DateTime value by adding the timespan value to the DateTime object value.

AddHours: It is used to return a new time by adding the hours to the value of the Datetime object.

AddYears: It is used to return the year by adding the year to the value of the DateTime object.

AddDays: It is used to return the new Day by adding the days to the value of the DateTime object.

AddMinutes: It is used to display the new time by adding the minutes to the Datetime object.

AddMonths: It is used to return the new time by adding the months to the value of the Datetime object.

AddSeconds: It is used to return the new time by adding the seconds to the value of the Datetime object.

IsLeapYear: It uses a Boolean value that represents whether the particular year is a leap year or not.

Syntax:
Let's create an object of the DateTime.

1. Dim obj_name As DateTime = New DateTime()  

Here, DateTime is a class for creating objects with the new keyword, and obj_name is the name of the
object.

Let's create a program to show the different functions of DateTime Class in VB.NET

DiffDateTime.vb

1.  Imports System.DateTime  
2. Module DiffDateTimevb  
3.     Sub Main()  
4.         ' Create DT as an instance of DateTime  
5.         Dim DT As DateTime = New DateTime()  
6.         Console.WriteLine("Default Date and Time is :{0}", DT)  
7.         Console.WriteLine()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

8.           
9.         Console.WriteLine(" Different function of DateTime")  
10.         Dim DoB As DateTime = New Date(1998, 9, 7, 12, 22, 30)  
11.         Console.WriteLine(" Day is : {0}", DoB.Day)  
12.         Console.WriteLine(" Month is : {0}", DoB.Month)  
13.         Console.WriteLine(" Year is : {0}", DoB.Year)  
14.         Console.WriteLine(" Hour is : {0}", DoB.Hour)  
15.         Console.WriteLine(" Minute is : {0}", DoB.Minute)  
16.         Console.WriteLine(" Second is : {0}", DoB.Second)  
17.         Console.WriteLine(" Millisecond is : {0}", DoB.Millisecond)  
18.         Console.WriteLine(" Day of Week is : {0}", DoB.DayOfWeek)  
19.         Console.WriteLine(" Day Of year is : {0}", DoB.DayOfYear)  
20.         Console.WriteLine(" Time of Day is : {0}", DoB.TimeOfDay)  
21.         Console.WriteLine(" Total Tick is : {0}", DoB.Ticks)  
22.   
23.         ' To get the Max Value of DateTime  
24.         Dim MDT As DateTime = DateTime.MaxValue  
25.         Console.WriteLine(" Max value of Date and Time is {0}", MDT)  
26.   
27.         ' To get the Min Value of DateTime  
28.         Dim MinDT As DateTime = DateTime.MinValue  
29.         Console.WriteLine(" Min value of Date and Time is {0}", MinDT)  
30.   
31.         ' Create a DateTime from string  
32.         Dim DString As String = "25/10/2020 5:10:29 PM"  
33.         Console.WriteLine("Display Date and Time from string : {0}", DString)  
34.         Console.WriteLine(" Press any key to exit?")  
35.         Console.ReadKey()  
36.     End Sub  
37. End Module  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Get the Current Date and Time


Let's create a program to get the current Date and Time in VB.NET.

CurrDateTime.vb

1. Imports System.DateTime  
2. Module CurrDateTime  
3.     Sub Main()  
4.   
5.         'Display current Date And Time in the following ways.  
6.         Dim CurrDT As Date = Date.Now  
7.         Console.WriteLine(" Current Date and Time is {0}", CurrDT)  
8.         Dim CT As DateTime = DateTime.Now ' Use of Now  
9.         Console.WriteLine(" Current Date and Time is {0}", CT)  
10.         Dim TD As DateTime = DateTime.Today ' Use of Today  
11.         Console.WriteLine(" Today Date is {0}", TD)  
12.         Dim Ut As DateTime = DateTime.UtcNow ' Use of UtcNow  
13.         Console.WriteLine(" Current UtC Date and Time Zone is {0}", Ut)  
14.   
15.         Console.WriteLine(" Today is {0} {1}.", CT.DayOfWeek, CT.Day)  
16.         Console.WriteLine(" The month number is {0} and the year {1}.", CT.Month, CT.Year)  
17.         Console.WriteLine(" {0} hours, {1} minutes and the seconds is {2}", CT.Hour, CT.Minute, CT.Second)  
18.         ' Current Time  
19.         Console.WriteLine(" Current Time is {0}", Now.ToLongTimeString)  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

20.         Console.WriteLine()  
21.         Console.WriteLine(" Press any key to exit...")  
22.         Console.ReadKey()  
23.     End Sub  
24. End Module  

Output:

Calculate DOB
To calculate DOB in a program, we need to use TimeSpan. The Timespan is used to store the difference
between two dates. The difference between TimeSpan and DateTime is that the TimeSpan represents
the time interval that can be a year or seconds, while DateTime represents the entire date over time.

In the following example, we will calculate the age by using the Date of Birth (DOB) of the user.

DofBirth.vb

1. Imports System.DateTime  
2. Module DofBirth  
3.     Sub Main()  
4.         'Dim age1 As Double  
5.         Console.WriteLine(" Enter Your Date of Birth in DD/MM/YYYY format")  
6.         Dim DB As DateTime = New DateTime()  
7.         DB = Console.ReadLine()  
8.         Dim age As TimeSpan = DateTime.Today - DB  
9.   
10.         Console.WriteLine(" Currently, You are {0} years old", Math.Floor(age.Days / 365.255))  
11.         Console.WriteLine(" And You are {0} days or {1} hours old", age.TotalDays, age.TotalHours)  
12.         Console.WriteLine(" Press any key to exit...")  
13.         Console.ReadKey()  
14.     End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

15. End Module  

Output:

Formatting Date
As the name defines, a date format is used in any application or web application to represent the date in
different formats. For example, we specified the Date literal as #5/5/2018# for the date May 5, 2018 that
represents the mm/dd/yyyy format of the date. We can also use the format dd/mm/yyyy to display the
date 12 August, 2019. If a locale user used another format like, yyyy/mm/dd, the literal would be invalid
or compile error.

Here, we used the Format function of string class to convert a date literal to custom or local format.
Further, we can also specify a predefined or user-defined format of the date.

Let's create a program to display the various format of date in VB.NET.

Date_Format.vb

1. Imports System.DateTime  
2. Module Date_Format  
3.     Sub Main()  
4.         Console.WriteLine(" Display the different Format of Dates in VB.NET ")  
5.         Dim FT As DateTime = New DateTime(2005, 7, 26, 0, 0, 0)  
6.         ' Use format Specifier to display the various format of the date.  
7.         Console.WriteLine(" Format of Date 'd' : " & FT.ToString("d"))  
8.         Console.WriteLine(" Format of Date 'D' : " & FT.ToString("D"))  
9.         Console.WriteLine(" Format of Date 'R' : " & FT.ToString("R"))  
10.         Console.WriteLine(" Format of Date 'y' : " & FT.ToString("y"))  
11.         Console.WriteLine(" Format of Date 'f' : " & FT.ToString("f"))  
12.         Console.WriteLine(" Format of Date 'F' : " & FT.ToString("F"))  
13.         Console.WriteLine(" Format of Date 't' : " & FT.ToString("t"))  
14.         Console.WriteLine(" Format of Date 'T' : " & FT.ToString("T"))  
15.         Console.WriteLine(" Format of Date 'g' : " & FT.ToString("g"))  
16.         Console.WriteLine(" Format of Date 'G' : " & FT.ToString("G"))  
17.         Console.WriteLine(" Format of Date 'M' : " & FT.ToString("M"))  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

18.         Console.WriteLine(" Press any key to exit...")  
19.         Console.ReadKey()  
20.     End Sub  
21. End Module  

Output:

VB.NET Hello World Program


In the previous topic, we have installed Visual Studio 2019 and created a console-based project with the
name MYConsoleApp1. Now in this project, we will create our Hello world VB.NET program.

A VB.NET define the following structure to create a program:

o Namespace declaration
o Procedure can be multiple
o Define a class or module
o Variables
o The Main procedure
o Statement and Expression
o Comments

Create a Hello_Program.vb file in MYConsoleApp1 project and write the following code:

Hello_Program.vb

1. Imports System 'System is a Namespace  
2. Module Hello_Program  
3.   
4.     Sub Main()  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

5.   
6.         Console.WriteLine("Hello, Welcome to the world of VB.NET")  
7.         Console.WriteLine("Press any key to continue...")  
8.         Console.ReadKey()  
9.   
10.     End Sub  
11.   
12. End Module  

Let's compile and run the above program by pressing the F5 key, we get the follwoiing output.

Output:

An Alternate method to compile and execute the VB.NET


program
We can also compile and execute the VB.NET program using the Command prompt instead of using the
Visual Studio IDE.

Step 1: After creating and saving the Hello_Program.vb file in the MYConsoleApp1 project, open the
command prompt and execute the commands, as we have shown in the prompt.

In place of MYConsoleApp1you can write your project name.

Step 2: After that, write vbc Hello_Program.vb, as shown below.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 3: If there is no error found at compile-time, it transfers the control in the next line for generating
the Hello_Pogram.exe file.

Step 4: Type Hello_Program to run the program. We get the following output.

Output:

Hello, Welcome to the world of VB.NET.

Now we will understand the basic structure of the VB.NET program:

o In VB.NET programming, the first line of the program is "Import System", where Imports is a
statement that inherit the system namespace. A System is a namespace that contains basic classes,
reference data types, events, attributes, and various inbuilt functions that help to run the program.
o The Second line defines the Module It specifies the VB.NET filename. As we know, VB.NET
language is a completely object-oriented language, so every program must contain a module or
class in which you can write your program that contains data and procedures within the module.

1. Module Module1  
2. End Module  
o You can define more than one procedure in classes and modules. Generally, the procedure contains
executable code to run. A procedure may contain the following function:

o Function
o Operator
o Sub
o Get
o Set
o AddHandler
o RemoveHandler
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

o Every program must contain a Main() method. In VB.NET, there is a Main() method or procedure
that represents the starting point to execute a program, as we have seen in C language, their entry
point is the main() function.
o A comment (') symbol is used to comment on a line that is ignored by the compiler in a program,
and it is a good practice to use comments for a better understanding of the program.
o The Console.WriteLine() is a method of the console class. It is used to print any text or messages in
the application. And the Console.ReadKey() is used to read a single character from the keyboard
back to the Visual Studio IDE.

Create a VB.NET program using Windows Form


If you want to create a new Window-based project in Visual Studio, follow the steps given below:

Step 1. Start the Visual Studio IDE.

Step 2. To create a project, click on File -> choose-> New-> Project

The following window appears on the screen.

Step 3: Select Windows Forms App (.NET Framework) and click on the Next button.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 4: Provide the Project name and location to store the project file using the browse button in Location.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 5: Click on the Create button. The following window appears on the screen.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 6: Now double click on the middle area of Form1.vb (Design) file, it shows the following code.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Form1.vb

1. Public Class Form1  
2.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         MsgBox("Welcome to the JavaTpoint")  
4.     End Sub  
5. End Class  

Step7: Save file as Form1.vb.

Step 8: To compile and run the Form1.vb file, press F5 button or Start button in Visual Studio. It shows the
following output.

VB.NET Label Control


In VB.NET, a label control is used to display descriptive text for the form in control. It does not participate
in user input or keyboard or mouse events. Also, we cannot rename labels at runtime. The labels are
defined in the class System.Windows.Forms namespace.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Let's create a label in the VB.NET Windows by using the following steps:

Step 1: We have to drag the Label control from the Toolbox and drop it on the Windows form, as shown
below.

Step 2: Once the Label is added to the form, we can set various properties to the Label by clicking on the
Label control.

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.

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.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

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


Furthermore, we can also refer to the VB.NET Microsoft documentation to get a complete list of Label

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.

BackColorChanged A BackColorChanged event occurs in the Label control when the value of the
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.
properties and events.

Let's create a program to display the Label controls in VB.NET.

Label.vb

1. Public Class Label  
2.     Private Sub Label_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javatpoint.com" 'Set the title for a Windows Form  
4.         Label1.Text = "Student Registration"  
5.         Label1.Font = New Font("Microsoft Sans Serif", "style = Bold", "Italic", 18)  ' Set Font style  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

6.         Label2.Text = "Student Name"  
7.         Label2.Font = New Font("Microsoft Sans Serif", "style = Bold", "Italic", 12)  
8.         Label3.Text = "Father's Name"  
9.         Label3.Font = New Font("Microsoft Sans Serif", "style = Bold", "Italic", 12)  
10.         Label4.Text = "Course "  
11.         Label4.Font = New Font("Microsoft Sans Serif", "style = Bold", "Italic", 12)  
12.         Label5.Text = "Address"  
13.         Label5.Font = New Font("Microsoft Sans Serif", "style = Bold", "Italic", 12)  
14.         Button1.Text = "Send"  
15.         TextBox1.Text = " "  
16.         TextBox2.Text = " "  
17.         TextBox3.Text = " "  
18.         RichTextBox1.Text = " "  
19.     End Sub  
20. End Class  

Output:

We have created 5 Labels on the Windows Form by using drag and drop operation in the above output.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Example2: Write a program to display only Labels on Windows forms.

Form1.vb

1. Public Class Form1  
2.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         'Set Text for Label1 and their property  
4.         Label1.Text = ?Welcome to JavaTpoint?  
5.         Label1.BorderStyle = BorderStyle.FixedSingle  
6.         Label1.TextAlign = ContentAlignment.MiddleCenter  
7.         'Set Text for Label2  
8.         Label2.Text = ? VB.NET Label Control?  
9.     End Sub  
10. End Class  

Output:

We can also load an image in the Label Control by using the following statement in the program.

1. Label1.Image = Image.FromFile(/"C:\Desktop\mypic.jpg")  

VB.NET Button Control


Button control is used to perform a click event in Windows Forms, and it can be clicked by a mouse or by
pressing Enter keys. It is used to submit all queries of the form by clicking the submit button or transfer
control to the next form. However, we can set the buttons on the form by using drag and drop operation.

Let's create a Button in VB.NET

Windowsform by using the following steps:


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Step 1: We have to drag the Button control from the Toolbox and drop it on the Windows form, as shown
below.

Step 2: Once the button is added to the form, we can set various properties of the Button by clicking on
the Button control.

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.

BackColor It is used to set the background color of the Button in the Windows form.

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

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


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

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.

Furthermore, we can also refer to the VB.NET Microsoft documentation to get a complete list of Button
properties and events.

Let's create a program to display a message on the Windows Forms using the button control in VB.NET.

Button_Control.vb

1. Public Class Button_Control  
2.     Private Sub Button_Control_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Button1.Text = "Click Me" ' Set the name of button  
4.     End Sub  
5.   
6.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
7.         MsgBox(" Visit here: https://www.javatpoint.com")   
8.  ' Display the message, when a user clicks on Click me button  
9.     End Sub  
10. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Now click on the 'Click Me' button, it shows the following message on the form.

Let's create another program that displays separate buttons on the form to perform different tasks.

Button_Control.vb

1. Public Class Button_Control  
2.     Private Sub Button_Control_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         ' Button1.Text = "Submit" ' Set the name of button  
4.         Button2.Text = "Exit"  
5.         Button3.Text = "Show Image"  
6.     End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

7.   
8.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
9.         MsgBox(" Visit here: https://www.javatpoint.com/vb-net") ' Display the message, when a user click on 
Click me button  
10.     End Sub  
11.   
12.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
13.         End ' It is used for terminating the program.  
14.     End Sub  
15.   
16.     Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click  
17.         PictureBox1.Visible = True  
18.     End Sub  
19.   
20.     Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click  
21.     End Sub  
22. End Class  

Output:

Now Click on the Click Me button, it shows the following message on the screen.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Now click on the Show Image button, it shows the following image on the screen.

Click on the Exit button to terminate the program.

VB.NET TextBox Control


A TextBox control is used to display, accept the text from the user as an input, or a single line of text on a
VB.NET Windows form at runtime. Furthermore, we can add multiple text and scroll bars in textbox control.
However, we can set the text on the textbox that displays on the form.

Let's create a TextBox control in the VB.NET

Windowsform by using the following steps:

Step 1: We have to drag the TextBox control from the Toolbox and drop it on the Windows form, as shown
below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 2: Once the TextBox is added to the form, we can set various properties of the TextBox by clicking on
the TextBox control.

VB.NET TextBox Properties


There are following properties of the TextBox control.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Properties Description

AutoCompleteMode It is used to get or set a value that indicates how the automatic completion
works for the textbox control.

Font It is used to set 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
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

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
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.

Furthermore, we can also refer to the VB.NET Microsoft documentation to get a complete list of TextBox
properties and events.

Let's create a program that displays the login details.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
JavatPoint1.vb

1. Public Class JavatPoint1  
2.     Private Sub JavatPoint1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "JavaTpoint.com" ' title name  
4.         Label1.Text = "User Login Details" ' Set the title name for Label1   
5.         Label2.Text = "Name"              ' Set the name for label2   
6.         Label3.Text = "Username"  ' Set the username for label2   
7.         Label4.Text = "Password"     ' Set the label name Passowrd  
8.         Text3.PasswordChar = "*"  
9.         Button1.Text = "Login"  ' Set the name of Button1 as Login  
10.         Button2.Text = "Exit"       ' Set the name of Button2 As Exit  
11.     End Sub  
12.   
13.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
14.         End ' terminate the program when the user clinks button 2  
15.     End Sub  
16.   
17.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
18.         Dim name As String  
19.         Dim Uname As String  
20.         Dim pass As String  
21.         name = text1.Text  
22.         Uname = Text2.Text  
23.         pass = Text3.Text  
24.         ' Display the user details, when the Button1 is clicked  
25.         MsgBox(" Your Name: " & name + vbCrLf + "Your UserName: " & Uname + vbCrLf + "Your Password: 
" & pass)  
26.     End Sub  
27. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Now enter all the details of the User Login form, it shows the following image, as shown below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Now, click on the Login button. It shows all the details filled by the user in the form.

The Exit button in the form used to terminate the program.

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. Furthermore, it also allows a user to
select an item from a drop-down list.

Let's create a ComboBox control in the VB.NET Windows by using the following steps.

Step 1: We need to drag the combo box control from the toolbox and drop it to the Windows form, as
shown below.

Step 2: Once the ComboBox is added to the form, we can set various properties of the ComboBox by
clicking on the ComboBox control.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
ComboBox Properties
There are following properties of the ComboBox control.

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
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

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
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

1. Public Class ComboBox_Control  
2.     Dim DT As Integer  
3.     Dim MM As String  
4.     Dim YY As Integer  
5.     Private Sub ComboBox_Control_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
6.         Me.Text = "JavaTpoint.com"  
7.         Label1.Text = "Display Calendar"  
8.         Label2.Text = "Get Date"  
9.         Button1.Text = "Date"  
10.         Button2.Text = "Exit"  
11.         ComboBox1.Items.Add("Date")  
12.         ComboBox1.Items.Add("01")  
13.         ComboBox1.Items.Add("02")  
14.         ComboBox1.Items.Add("03")  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

15.         ComboBox1.Items.Add("04")  
16.         ComboBox1.Items.Add("05")  
17.         ComboBox1.Items.Add("06")  
18.         ComboBox1.Items.Add("07")  
19.         ComboBox1.Items.Add("08")  
20.         ComboBox1.Items.Add("09")  
21.         ComboBox2.Items.Add("Month")  
22.         ComboBox2.Items.Add("January")  
23.         ComboBox2.Items.Add("February")  
24.         ComboBox2.Items.Add("March")  
25.         ComboBox2.Items.Add("May")  
26.         ComboBox2.Items.Add("June")  
27.         ComboBox2.Items.Add("July")  
28.         ComboBox3.Items.Add("Year")  
29.         ComboBox3.Items.Add("2016")  
30.         ComboBox3.Items.Add("2017")  
31.         ComboBox3.Items.Add("2018")  
32.         ComboBox3.Items.Add("2019")  
33.         ComboBox3.Items.Add("2020")  
34.     End Sub  
35.   
36.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
37.         DT = ComboBox1.Text  
38.         MM = ComboBox2.Text  
39.         YY = ComboBox3.Text  
40.         MsgBox("Month " & MM + vbCrLf + "Year " & YY)  
41.     End Sub  
42.   
43.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
44.         End  
45.     End Sub  
46. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Now select the day, month, and year from dropdown box and then click on the Date button to display the
date in the form.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

VB.NET 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. Furthermore, we can add or design the list box by using the
properties and events window at runtime.

Let's create a ListBox control in the VB.NET Windows by using the following steps.

Step 1: Drag the ListBox control from the Toolbox and drop it to the Windows form, as shown below.

Step 2: Once the ListBox is added to the Form, we can set various properties of the Listbox by clicking on
the ListBox control.

ListBox Properties
There are following properties of the ListBox control.

ListBox Methods

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.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

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.

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.

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

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

1. Public Class Listbx  
2.     Private Sub Listbx_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         ' set the title of the Form.  
4.         Me.Text = "JavaTpoint.com"  
5.         ' Add the items into the ListBox  
6.         ListBox1.Items.Add("Earth")  
7.         ListBox1.Items.Add("Mercury")  
8.         ListBox1.Items.Add("Mars")  
9.         ListBox1.Items.Add("Jupiter")  
10.         ListBox1.Items.Add("Venus")  
11.         ListBox1.Items.Add("Neptune")  
12.         ListBox1.Items.Add("Uranus")  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

13.         ' Set the name of the Button1 and Button2  
14.         Button1.Text = "Show"  
15.         Button2.Text = "Exit"  
16.         Label2.Text = "Select the solar system from the ListBox"  
17.     End Sub  
18.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
19.         Dim lt As String  ' define a local variable.  
20.         lt = ListBox1.Text  'accept the data from the ListBox1  
21.         MsgBox(" Selected Solar System is " & lt)  ' Display the selected item   
22.     End Sub  
23.     Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.Selecte
dIndexChanged  
24.         Label1.Text = ListBox1.SelectedItem.ToString()  'When a user clicks on an item, it displays the item na
me.  
25.     End Sub  
26.   
27.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
28.         End 'End or exit an application  
29.     End Sub  
30. End Class  

Output:

Now select an item from the list. We have selected Jupiter.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Click on the Show button to display the selected item in Windows Form, as follows.

VB.NET 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.

Let's create a CheckedListBox control in the VB.NET Windows form using the following steps.

Step 1: Drag the CheckedListBox control from the Toolbox and drop it to the Windows form, as shown
below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 2: Once the CheckedListBox is added to the Form, we can set various properties of the
CheckedListbox by clicking on the CheckedListBox control.

CheckedListBox Properties
There are following properties of the CheckedListBox control.

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.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

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.

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of CheckedListBox properties and methods.

Let's create a program to select or check more than one item from the CheckedListBox in the VB .NET form.

CheqListvb.vb

1. Public Class CheqListvb  
2.     Private Sub CheqListvb_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

3.         Me.Text = " JavaTpoint.com"  
4.         CheckedListBox1.Items.Add("VB.NET")  
5.         CheckedListBox1.Items.Add("Java")  
6.         CheckedListBox1.Items.Add("Python")  
7.         CheckedListBox1.Items.Add("C")  
8.         CheckedListBox1.Items.Add("C#")  
9.         CheckedListBox1.Items.Add("PHP")  
10.         CheckedListBox1.Items.Add("JavaScript")  
11.         CheckedListBox1.Items.Add("Ruby Language")  
12.         CheckedListBox1.Items.Add("Android")  
13.         CheckedListBox1.Items.Add("Perl")  
14.         Label1.Text = "Choose one or more programming languages of your choice. "  
15.         Button1.Text = "Select"  
16.         Button2.Text = "Exit"  
17.     End Sub  
18.   
19.     ' To submit the checked items, click on Button1 or Select  
20.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
21.         Dim cheq As New System.Text.StringBuilder  
22.         For Each item In CheckedListBox1.CheckedItems  
23.             cheq.Append(item)  
24.             cheq.Append(" ")  
25.         Next  
26.         MessageBox.Show(" Your Checked Items are : " & cheq.ToString())  
27.   
28.     End Sub  
29.   
30.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
31.         End 'terminate the program  
32.     End Sub  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

In the above list, we can select more than one item from the CheckedListBox in Windows Form.

After that, click on the Select button to display the selected item in Windows Form.

RadioButton Control
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
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, we can use the radio button.
The RadioButton is mutually exclusive that represents only one item is active and the remains unchecked
in the form.

Let's create a RadioButton control in the VB.NET Windows by using the following steps.

Step 1: Drag the RadioButton control from the toolbox and drop it to the Windows form, as shown
below.

Step 2: Once the RadioButton is added to the form, we can set various properties of the RadioButton by
clicking on the Radio control.

RadioButton Properties
There are following properties of the VB.NET RadioButton control.

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).


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

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.

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

1. Public Class RadioBtn  
2.     Private Sub RadioBtn_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

3.         Me.Text = "javaTpoint.com" ' Set the title of the form  
4.         Label1.Text = "Select the Gender"  
5.         RadioButton1.Text = "Male"  ' Set the radiobutton1 and radiobutton2  
6.         RadioButton2.Text = "Female"  
7.         RadioButton3.Text = "Transgender"  
8.         Button1.Text = "Submit"   ' Set the button name  
9.         Button2.Text = "Exit"  
10.     End Sub  
11.   
12.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
13.         Dim gen As String  
14.         If RadioButton1.Checked = True Then  
15.             gen = "Male"  
16.             MsgBox(" Your gender is : " & gen)  
17.   
18.         ElseIf RadioButton2.Checked = True Then  
19.             gen = "Female"  
20.             MsgBox(" Your gender is : " & gen)  
21.         Else  
22.             gen = "Transgender"  
23.             MsgBox(" You have Selected the gender : " & gen)  
24.         End If  
25.   
26.     End Sub  
27.   
28.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
29.         End 'Terminate the program  
30.     End Sub  
31. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Click on the Submit button. It shows the following message on the screen.

VB.NET 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.

Let's create a CheckBox control in the VB.NET Windows form using the following steps.

Step 1: We need to drag the CheckBox control from the toolbox and drop it to the Windows form, as
shown below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 2: Once the CheckBox is added to the form, we can set various properties of the checkbox by clicking
on the CheckBox control.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
CheckBox Properties
There are some properties of the VB.NET CheckBox control.

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.

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

Appearanc The Appearance property is used to display the appearance of a checkbox control by
e 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.

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


d

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.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Event Description

CheckedChanged The CheckedChanged event is found when the value of the checked property
is changed to CheckBox.

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

1. Public Class Checkbxvb  
2.     Private Sub Checkbxvb_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javaTpoint.com" ' Set the title name of the form  
4.         Label1.Text = "Select the fruits name"  
5.         CheckBox1.Text = "Apple"  
6.         CheckBox2.Text = "Mango"  
7.         CheckBox3.Text = "Banana"  
8.         CheckBox4.Text = "Orange"  
9.         CheckBox5.Text = "Potato"  
10.         CheckBox6.Text = "Tomato"  
11.         Button1.Text = "Submit"  
12.         Button2.Text = "Close"  
13.     End Sub  
14.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
15.         Dim fruit As String  
16.         fruit = " "  
17.         If CheckBox1.Checked = True Then  
18.             fruit = "Apple"  
19.         End If  
20.         If CheckBox2.Checked = True Then  
21.             'fruit = CheckBox2.Text  
22.             fruit = fruit & " Mango"  
23.         End If  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

24.         If CheckBox3.Checked = True Then  
25.             fruit = fruit & " Banana"  
26.         End If  
27.         If CheckBox4.Checked = True Then  
28.             fruit = fruit & " Orange"  
29.         End If  
30.         If CheckBox5.Checked = True Then  
31.             fruit = fruit & " Potato"  
32.         End If  
33.         If CheckBox6.Checked = True Then  
34.             fruit = fruit & " Tomato"  
35.         End If  
36.         If fruit.Length <> 0 Then  
37.             MsgBox(" Selected items " & fruit)  
38.         End If  
39.         CheckBox1.ThreeState = True  
40.     End Sub  
41.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
42.         End 'terminate the program  
43.     End Sub  
44. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Now select the fruit name by clicking on the items.

Now click on the Submit button, it displays the following output on your screen.

VB.NET 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.

Let's create a PictureBox control in the VB.NET Windows form using the following steps.

Step 1: We have to find the PictureBox control from the toolbox and then drag and drop the PictureBox
control onto the window form, as shown below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 2: Once the PictureBox is added to the form, we can set various properties of the image by clicking
on the PictureBox control.

Properties of the PictureBox


There are following properties of the VB.NET PictureBox control.

Property Description

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

BackgroundImage It is used to set the background image of a window form by setting or getting
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


PictureBox control.

Text It is used to set text for the picture box controls in the window form.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

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.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of PictureBox control properties, methods, and events in the VB.NET.

Let's create a program to display an image in the VB.NET form.

Picturebx.vb

1. Public Class Picturebx  
2.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
3.         'Dim Str As String = "C:\Users\AMIT YADAV\Desktop\"  
4.         PictureBox1.Image = Image.FromFile("C:\Users\AMIT YADAV\Desktop\jtp2.png")  
5.         PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage  
6.         PictureBox1.Height = 250  
7.         PictureBox1.Width = 400  
8.         Label1.Visible = False  
9.     End Sub  
10.     Private Sub Picturebx_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
11.         Me.Text = "javaTpoint.com" 'Set the title name for the form  
12.         Button1.Text = "Show"  
13.         Label1.Text = "Click to display the image"  
14.         Label1.ForeColor = ForeColor.Green  
15.     End Sub  
16. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Now click on the Show button to display an image in the windows form.

VB.NET 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.

Let's create a ProgressBar by dragging a ProgressBar control from the toolbox and dropping it to
the Windows form.

Step 1: The first step is to drag the ProgressBar control from the toolbox and drop it on to the Form.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 2: Once the ProgressBar is added to the Form, we can set various properties of the ProgressBar by
clicking on the ProgressBar control.

Properties of the ProgressBar Control


There are following properties of the VB.NET ProgressBar control.

Property Description

BackgroundImage The BackgroundImage property is used to set the background image in


the progressbar control.

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


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.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

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,
d the BackgroundImageChanged event changes.

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.

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of ProgressBar control properties, methods, and events in the VB.NET.

Let's create a program to display the progress status in the VB.NET Windows form.

Progressbr.vb
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

1. Public Class Progressbr  
2.     Private Sub Progressbr_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javaTpoint.com" 'Set the title name for the form  
4.         Button1.Text = "Show"  
5.         Label1.Text = "Click to display the progress status of the ProgressBar"  
6.         Label1.ForeColor = ForeColor.Green  
7.         ProgressBar1.Visible = False  
8.   
9.         'create a progress bars  
10.         Dim Progressbr2 As ProgressBar = New ProgressBar()  
11.   
12.         'set the progressbar position  
13.         Progressbr2.Location = New Point(60, 70)  
14.         'set the values for Progressbr2  
15.         Progressbr2.Minimum = 0  
16.         Progressbr2.Maximum = 500  
17.         Progressbr2.Value = 470  
18.   
19.         'add the progress bar status to the form.  
20.         Me.Controls.Add(Progressbr2)  
21.   
22.     End Sub  
23.   
24.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
25.         ProgressBar1.Visible = True  
26.   
27.         Dim i As Integer  
28.         ProgressBar1.Minimum = 0  
29.         ProgressBar1.Maximum = 300  
30.   
31.         For i = 0 To 300 Step 1  
32.             ProgressBar1.Value = i  
33.             If i > ProgressBar1.Maximum Then  
34.                 i = ProgressBar1.Maximum  
35.             End If  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

36.         Next  
37.         MsgBox("Successfully Completed")  
38.     End Sub  
39. End Class  

Output:

Click on the Show button to display the progress status at run time in Windows Form.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

And when the progress status reaches the progress bar's maximum value, it displays the following
message.

VB.NET ScrollBars Control


A ScrollBar control is used to create and display vertical and horizontal scroll bars on the Windows form. It
is used when we have large information in a form, and we are unable to see all the data. Therefore, we
used VB.NET ScrollBar control. Generally, ScrollBar is of two types: HScrollBar for displaying scroll bars and
VScrollBar for displaying Vertical Scroll bars.

Let's create a ScrollBar control in the VB.NET

Windowsform using the following steps.

Step 1: The first step is to drag the HScrollBar and VScrollBar control from the toolbox and drop it on to
the form.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 2: Once the ScrollBar is added to the form, we can set various properties of the ScrollBar by clicking
on the HScrollBar and VScrollBar control.

Properties of the ScrollBar Control


There are following properties of the VB.NET ScrollBar control.

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
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

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.

DefaultImeMode It is used to get the default input method Editor (IME) that are supported by
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.

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.

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of ScrollBar control properties, methods, and events in the VB.NET.

Let's create a simple program to understand the use of ScrollBar Control in the VB.NET Windows Forms.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
ScrollBar.vb

1. Public Class ScrollBar  
2.     Private Sub ScrollBar_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javatpoint.com"  'Set the title for a Windows Form  
4.         Label1.Text = "Use of ScrollBar in Windows Form"  
5.         Label1.ForeColor = Color.Blue  
6.         Me.AutoScroll = True  
7.         Me.VScrollBar1.Minimum = 0  
8.         Me.VScrollBar1.Maximum = 100  
9.         Me.VScrollBar1.Value = 0  
10.         Me.VScrollBar1.BackColor = Color.Blue  
11.         Me.HScrollBar1.Minimum = 0  
12.         Me.HScrollBar1.Maximum = 100  
13.         Me.HScrollBar1.Value = 35  
14.     End Sub  
15. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

VB.NET 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. By default, the Value property returns the current date and time in
the DateTimePicker.

Let's create a DateTimePicker control in the VB.NET Windows form using the following steps.

Step 1: The first step is to drag the DateTimePicker control from the toolbox and drop it on to the form.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 2: Once the DateTimePicker is added to the form, we can set various properties of
the DateTimePicker by clicking on the DateTimePicker control.

Properties of the DateTimePicker Control


There are some properties of the VB.NET 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.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Format The Format property of the DateTimePicker is used to set the format for the
Date and time displayed in the Windows Form.

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.

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

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.

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of DateTimePicker control properties, and methods in the VB.NET.

Let's create a program of DateTimePicker control in the VB.NET form.

DateTime.vb

1. Public Class DateTime  
2.     Private Sub DateTime_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javatpoint.com"  
4.         Button1.Text = "Calculate Days"  
5.         Label1.Text = "Calculate the total days from your date of birth to the current date."  
6.         Label2.Text = "Total Days"  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

7.         Label3.Text = "Select the DOB"  
8.         Label4.Text = "Current Date"  
9.         DateTimePicker1.Format = DateTimePickerFormat.Long  
10.     End Sub  
11.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
12.         Dim dp As Date = DateTimePicker1.Value  
13.         Dim dp2 As Date = DateTimePicker2.Value  
14.         Dim result As TimeSpan = dp.Subtract(dp2)  
15.         Dim ds As Integer = result.TotalDays  
16.         TextBox1.Text = ds  
17.         TextBox1.ForeColor = ForeColor.Red  
18.         MsgBox(" Days = " & ds)  
19.     End Sub  
20. End Class  

Output:

Now, we select the date of birth from the DateTimePicker Control.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

After selecting the DOB and the Current date from the DateTimePicker Control, now click on
the Calculate button, and it shows the following result.

VB.NET TreeView Control


The TreeView control is used to display a hierarchical representation of the same data in a tree structure.
The top-level in the tree view is the root node with one or more child nodes. In addition, the root node can
be contracted or expanded by clicking on the plus sign (+) button. It is also useful to provide the full path
of the root node to the child node.

Let's create a TreeView control in the VB.NET Windows form using the following steps.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Step : We have to find the TreeView control from the toolbox and then drag and drop the TreeView
control onto the window form, as shown below.

Step 2: Once the TreeView is added to the form, we can set various properties of the TreeView by clicking
on the TreeView control.

Properties of the TreeView Control


There are following properties of the TreeView control.

Properties Description

Nodes The nodes property of the tree view control is used to gather all the nodes used in
the tree.

SelectedNode It is used to obtain or set the tree node that is selected in the tree view control.

ShowRootLines It gets or sets a value that represents whether you want to draw lines between the
tree nodes connected with the root of the tree view.

Path Separator The Path Separator property of the Tree View Control is used to set a delimiter
string between the tree node paths.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

ShowPlusMinu It is used to get or set a value representing whether you want to display the plus
s (+) or minus sign button next to tree nodes containing the child nodes.

ShowLines It takes a value representing whether you want to draw lines between the tree
nodes of the tree view control.

TopNode It is used to get or set full visible tree nodes on top of other nodes in the tree view
control.

VisibleCount It is used to obtain the fully visible tree node in the tree view control.

ItemHeight The ItemHeight property is used to set the height of each tree node in control.

Scrollable The Scrollable property is used in the tree-view to display the scroll bar by setting
the value in control.

Methods of the TreeView Control

Method Description

GetNodeAt A GetNodeAt() method is used to get a node at the specified location of the tree
view control.

Sort() A Sort method is used to sort the tree nodes that are available in the tree view
control.

ExpandAll() As the name suggests, an ExpandAll method is used to expand all the tree nodes.

GetNodeCount It is used to count the number of nodes that are available in the tree view control.

CollapseAll It is used to collapse all tree nodes, including all child nodes in the tree view control.

ToString ToString method is used to return the name of the string that is in the tree view
control.

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of TreeView control properties and methods.

Let's create a program to insert a node in the tree view control of the VB.NET form.

treeView.vb

1. Public Class treeView  
2.     Private Sub treeView_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javaTpoint.com" 'Set the title name for the Windows form.  
4.         Button1.Text = "Add New Node" 'Set the name of button  
5.     End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

6.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
7.         Dim nd As String  
8.         nd = InputBox("Enter Node name")  ' takes input from the user  
9.         If TreeView1.SelectedNode Is Nothing Then  ' insert a new node.  
10.             TreeView1.Nodes.Add(nd, nd)  
11.         Else  
12.             TreeView1.SelectedNode.Nodes.Add(nd, nd)   ' insert into the sub node or child node  
13.         End If  
14.     End Sub  
15. End Class  

Output:

Click on the Add New Node button to insert a new node into the tree view control. It displays the
following image on the monitor.

Click on the OK button to insert the 'VB.NET' node in the tree view control.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Similarly, we can create all-new nodes in the TreeView control, as shown below.

VB.NET ListView Control


The ListView Controls are used to display a collection of items in the Windows Forms. It uses one of the
view lists, such as LargeIcon, SmallIcon, Details, List, and Tile. Furthermore, the ListView allows the user to
add or remove icons from the ListView Control.

Let's create a ListView control in the VB.NET Windows form by using the following steps.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Step 1: We have to find the ListView control from the toolbox and then drag and drop the ListView control
onto the window form, as shown below.

Step 2: Once the ListView is added to the form, we can set various properties of the List by clicking on the
ListView control.

Properties of the ListView Control


There are following properties of ListView control.

Properties Description

Alignment The Alignment property is used to set the alignment for the item in the ListvVew
Control.

Activation The Activation property is used to get or set a user-requested action to activate an
item.

CheckBoxes The CheckBoxes property sets a value to display the checkbox that appears next to
each item in the list view control.

Columns The Columns property is used to display the collection of columns header in the
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

ListView Control.

CheckIndices The CheckIndices property is used to get all checked items in the ListView Control.

GridLines The GridLines Property is used to display the gridlines between the rows and
columns that contain the items and subitems in the ListView Control.

Items It is used to collect the collection of the items that are in the ListView Control.

LargeImageList It is used to set or get ImageList to display it as a large icon in the ListView Control.

HeaderStyle It is used to set or get the column header style in the ListView control.

MultiSelect The MultiSelect property is used to set a value that allows selecting more than items
in the ListView control.

SelectedItems It is used to obtain all selected items in the ListView control.

ShowGroups The ShowGroups property set a value that represents whether the ListView items
are displayed in groups.

SmallImageList It is used to set or get ImageList to display the image as a small icon in the ListView
control.

TopItem The TopItem property is used to set or get the first item in control.

View The View property is used to set the items displayed in the List view. The View
property has the following values:
SmallIcon: It is used to display small size icons.
List: It is used to display items in a list, and it only shows captions.
LargeIcon: It is used to display large size icons.
Report: It is used to display items and its sub-items.

Methods of the ListView Control

Method Description

ArrangeIcons() The ArrangeIcons method is used to arrange all the items displayed as icons in
the ListView control.

FindItemWithText() It is used to search the first ListViewItem that started with the given text value.

GetItemAt() The GetItemAt method is used to get an item at the specified location of the
ListView control.

Clear() The Clear method is used to clear all the items and columns from the ListView
control.

Sort() The Sort method is used to sort items of the ListView.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Events of the ListView Control

There are following events of the ListView control.

Events Description

ItemActivate The ItemActivate event occurred when an item activated in the ListView control.

ItemChecked The ItemChecked event is found in the ListView control when the checked state
of an item changes.

TextChanged The TextChanged event is found in the ListView control when the property of the
text changes.

ItemCheck When the status of a check item changes, the ItemCheck event is found in the
list view control.

AfterLabelEditEven It occurs when the user in the ListView control edits the label for an item.
t

Let's create a program to insert the records in the ListView control of the VB.NET Windows form.

List_View.vb

1. Public Class List_View  
2.     Private Sub List_View_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javatpoint.com" 'Set the title for the Windows form  
4.         ListView1.View = View.Details  ' Display the List in details  
5.         ListView1.GridLines = True   ' Set the Grid lines   
6.         Label1.Text = "Enter the Roll No." ' Set the name of Labels  
7.         Label2.Text = "Enter Your Name"  
8.         Label3.Text = "Enter Your Email"  
9.         Label4.Text = "Enter the Course"  
10.         Label5.Text = "Student details"  
11.         ListView1.Columns.Add("Roll No", 70, HorizontalAlignment.Left) ' set the name of column  
12.         ListView1.Columns.Add("Name", 100, HorizontalAlignment.Left) ' set the name of column  
13.         ListView1.Columns.Add("Email", 150, HorizontalAlignment.Left) ' set the name of column  
14.         ListView1.Columns.Add("Course", 100, HorizontalAlignment.Left) ' set the name of column  
15.         ListView1.BackColor = Color.LightSkyBlue  
16.         Button1.Text = "Add New Entry"  
17.         Button1.ForeColor = Color.White  
18.         Button1.BackColor = Color.Green  
19.         Label5.ForeColor = Color.Red  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

20.         Button2.Text = "Exit"  
21.         Button2.BackColor = Color.Red  
22.     End Sub  
23.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
24.         Dim str(4) As String  
25.         Dim itm As ListViewItem  
26.         str(0) = TextBox1.Text  'Accept value from the user.  
27.         str(1) = TextBox2.Text  
28.         str(2) = TextBox3.Text  
29.         str(3) = TextBox4.Text  
30.         itm = New ListViewItem(str)  
31.         ListView1.Items.Add(itm) 'Add the items into the ListView  
32.     End Sub  
33.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
34.         End 'Exit from the program  
35.     End Sub  
36. End Class  

Output:

Now, we fill all the details of the Student that is asked in the Form.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Now, click on the Add New Entry button. It displays the record in the ListView control or in Student details
table, as shown below.

Similarly, we have added the following student details in the form.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

VB.NET Menu Control


A menu is used as a menu bar in the Windows form that contains a list of related commands, and it is
implemented through MenuStrip Control. The Menu control is also known as the
VB.NET MenuStrip Control. The menu items are created with ToolStripMenuItem Objects. Furthermore,
the ToolStripDropDownMenu and ToolStripMenuItem objects enable full control over the structure,
appearance, functionalities to create menu items, submenus, and drop-down menus in
a VB.NET application.

Let's create a MenuBar by dragging a MenuStrip control from the toolbox and dropping it to
the Windows form.

Step 1. Drag the MenuStrip control from the toolbox and drop it on to the Form.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 2: Once the MenuStrip is added to the form, we can set various properties of the Menu by clicking on
the MenuStrip control.

Properties of the MenuStrip Control


There are following properties of the VB.NET MenuStrip control.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Properties Description

CanOverflow The CanOverflow property is used to authenticate whether the control supports
overflow functionality by setting values in the MenuStrip control.

Stretch The Stretch property is used to obtain a value that specifies whether the
menustrip stretches from end to end in the MenuStrip control.

GripStyle The GripStyle property obtains or sets the visibility of the grip that uses the
reposition of the menu strip control.

ShowItemToolTip It is used to obtain or set the value that determines if the ToolTips are displayed
s for the MenuStrip Control.

DefaultSize The DefaultSize property is used to get the default horizontal and vertical
dimension of the MenuStrip in pixel when it is first created.

Methods of the MenuStrip Control

Method Description

CreateAccessibilityInstance() It is used to create a new accessibility instance for the MenuStrip


Control.

ProcessCmdKey() The ProcessCmdKey method is used to process the command key in


the MenuStrip Control.

CreateDefaultItem() The CreateDefaultItem method is used to create a ToolStripMenuItem


with the specified text, image, and event handlers for the new
MenuStrip.

OnMenuActivate() It is used to initiate the MenuActivate event in the MenuStrip control.

OnMenuDeactivate() It is used to start the MenuDeactivate event in the MenuStrip control.

Events of the MenuStrip Control

Events Description

MenuActivate When a user uses a menu bar control with a mouse or keyboard, a MenuActivate
event occurs.

MenuDeactivate The MenuDeactivate event occurs when the MenuStrip control is deactivated in
the Windows form.

Let's create a program to display the menu bar in the Windows form.

In this image, we have created the menu and sub-items of the menu bar in the form.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Now, we write the Shortcut keys for the File subitems, such as New -> Ctrl + N, Open -> Ctrl + O, etc.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
After that, we can see the subitems of the Files with their Shortcut keys, as shown below.

Menus.vb

1. Public Class Menus  
2.     Private Sub Menus_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javatpoint.com" 'set the title of the bar  
4.         BackColor = Color.SkyBlue  
5.     End Sub  
6.   
7.     Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuIt
em.Click  
8.         Me.Dispose() ' exit from the form  
9.     End Sub  
10. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Click on the File menu that shows the multiple options related to files.

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.

1. MidParent: The MidParent property is used to set a parent form to a child form.


2. ActiveMdiChild: The ActiveMdiChild property is used to get the reference of the current child form.
3. IsMdiContainer: The IsMdiContainer property set a Boolean value to True that represents the
creation of a form as an MDI form.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

4. LayoutMdi(): The LayoutMdi() method is used to arrange the child forms in the parent or main
form.
5. 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.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

In the above image, 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

1. Public Class Form2  
2.     Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "Feedback form" ' Set the title of the form  
4.         Label1.Text = " Fill the Feedback form"  
5.         Button1.Text = "Submit"  
6.         Button1.BackColor = Color.SkyBlue  
7.         Button2.Text = "Cancel"  
8.         Button2.BackColor = Color.Red  
9.     End Sub  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

10.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
11.         MsgBox(" Successfully submit the feedback form")  
12.     End Sub  
13.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
14.         Me.Dispose() ' end the form2  
15.     End Sub  
16. End Class  

Another Child Form with the name Form3.

Form3.vb

1. Public Class Form3  
2.     Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Label1.Text = "Welcome to JavaTpoint Tutorial Site"  
4.         Label.BackColor = Color.Green  
5.         Label2.Text = "This is the VB.NET Tutorial and we are learning the VB.NET MDI Form"  
6.         Label2.BackColor = Color.SkyBlue  
7.     End Sub  
8. 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

1. Public Class MDI_Form  
2.     Private Sub MDI_Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         IsMdiContainer = True 'Set the Boolean value to true to create the form as an MDI form.  
4.         Me.Text = "javatpoint.com" 'set the title of the form  
5.         PictureBox1.Image = Image.FromFile("C:\Users\AMIT YADAV\Desktop\jtp2.png")  
6.         PictureBox1.Height = 550  
7.         PictureBox1.Width = 750  
8.     End Sub  
9.     Private Sub FeedbackFormToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles Feedbac
kFormToolStripMenuItem.Click  
10.         PictureBox1.Visible = False  
11.         Dim fm2 As New Form2  
12.         fm2.MdiParent = Me 'define the parent of form3, where Me represents the same form  
13.         fm2.Show() 'Display the form3  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

14.     End Sub  
15.     Private Sub VBNETToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VBNETToolStrip
MenuItem.Click  
16.         PictureBox1.Visible = False  
17.         Dim fm3 As New Form3  
18.         fm3.MdiParent = Me 'define the parent of form3, where Me represent the same form  
19.         fm3.Show() 'Display the form3  
20.     End Sub  
21. End Class  

Output:

After that, click on the Menu button, it shows two sub-items of the Menu as Feedback Form and VB.NET.
We have clicked on the Feedback Form that displays the following form on the window.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

When we click on the Menu item, it shows the following image on the screen.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

VB.NET Dialog Box


A Dialog box is a temporary Window for an application that accepts user response through mouse or
keyboard to open a file, save a file, notifications, alert messages, color, print, openfile dialog box, etc. It is
also useful to create communication and interaction between the user and the application. Furthermore,
the dialog box appears in a form when the program needs to interact with users, such as when an error
occurs, an alert message, acknowledgment from the user or when the program requires immediate action
or whether the decision is to be saved based on the changes.

All VB.NET Dialog box inherits the CommonDialog class and overrides the RunDialog() method of the
base class to create the OpenFileDialog box, PrintDialogbox, Color, and Font Dialog box.
The RunDialog() method is automatically called in a Windows form when the dialog box calls
its ShowDialog() method.

There are following functions of the ShowDialog() method that can be called at run time in the Windows
Form.

o Abort: The Abort Dialog box is used when a user clicks on the Abort button to return the
DialogResult.Abort value.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

o Ignore: The Ignore Dialog box is used when a user clicks on the Ignore button to return the
DialogResult.Ignore.
o None: It is used to return nothing when the user clicks on the None button, and the dialog box is
continued running.
o OK: When the user clicks the OK button of the Dialog box, it returns a DialogResult.OK,
o Cancel: When a user clicks on the Cancel button of the Dialog Box, it returns DialogResult.Cancel,
o Yes: When a user clicks the Yes button of the dialog box, it returns DialogResult.Yes.
o Retry: When a user clicks on the Dialog Box Retry button, it returns a DialogResult.Retry,
o No: When a user clicks on the No button of the Dialog box, it returns DialogResult.No,

There are the commonly used dialog box controls in the VB.NET Windows Form.

1. Color Dialog Box: It is used to display the color dialog box that allows the user to select a color
from the predefined colors or specify the custom colors.
2. Font DialogBox: It is used to create a Font dialog box that allows the user to select the font, font
size, color, and style to be applied to the current text selection.
3. OpenFile Dialog Box: It is used to create a prompt box that allows the users to select a file to open
and allows the selection of multiple files.
4. Print Dialog Box: It is used to create a print dialog box that allows the user to print documents by
selecting the printer and setting of the page printed through the Windows application.

Let's create a simple program to display the dialog box in the VB.NET Windows Forms.

Dialog.vb

1. Public Class Dialog  
2.     Private Sub Dialog_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Button1.Text = "Click Me" 'Set the name of button  
4.         Me.Text = "javatpoint.com" ' Set the title name for the Windows Form  
5.         Button1.BackColor = Color.Green ' Background color of the button  
6.     End Sub  
7.   
8.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
9.         Dim result1 As DialogResult = MessageBox.Show("Is VB.NET programming language easy to learn?",  
10.     "Important Question",  
11.     MessageBoxButtons.YesNo)  
12.     End Sub  
13. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Now, click on the Click Me button of the Windows Form, it displays the dialog box, as shown below.

B.NET Color Dialog Box


The Color Dialog box is used to display the Color dialog box and the selection of colors on the Microsoft
Windows Application. It allows users to set or change the color of an object, such as the background color
of a control or the color used to paint an object. Furthermore, the control dialog box also allows the facility
to the user to create a new color by mixing all other colors of the Color Dialog Box.

Let's create a Color Dialog in the VB.NET Windows form by using the following steps.

Step 1: Drag the Color Dialog from the toolbox and drop it to the Windows form, as shown below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 2: Once the Color Dialog is added to the form, we can set various properties of the Color by clicking
on the Color Dialog.

Properties of Color DialogBox


There are following properties of the Color Dialog Box in the Windows Form.

Properties Description

AllowFullOpen The AllowFullOpen property enables the user to set custom colors in Windows
Forms by setting values in the color dialog box.

Color The Color property is used to set or get the user's selected color from the Color
Dialog box.

FullOpen The FullOpen property is used to set a value representing whether the custom
colors will be displayed when the dialog box is opened.

AnyColor The AnyColor property takes a value that is used to display all available colors in the
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Color dialog box with a set of basic colors.

ShowHelp ShowHelp property enables the user to display the help button in the Color Dialog
box by setting a value in the dialog box.

CustomColors It is used to set the custom colors that are displayed on the dialog box.

SolidColorOnl The SolidColorOnly property is used to set a value representing whether the dialog
y box restricts the user from selecting only solid colors.

Events of Color DialogBox

Events Description

Disposed When control or component is terminated by calling the Dispose method, a Dispose
event occurs.

HelpRequest When a user clicks the help button of the Color dialog box, the HelpRequest event is
called.

Methods of Color DialogBox

Method Description

ShowDialog() The ShowDialog () method is used to run a common dialog box with the default
setting.

Dispose() The Dispose() method is used to free all resources used by the Control or
component in the Color Dialog Box.

Equals() The Equals() method is used to check whether the current or defined object is the
same.

OnHelpRequest() It is used to call the HelpRequest event in the dialog box.

Reset() The Reset() method is used to reset all changes to their default values. For
example, the last selected color to be black, and the custom color to be their
default values.

RunDialog() It is used to override a derived class to create a common dialog box.

Let's create a simple program to display the Color dialog box in the VB.NET Windows Forms.

ColorDialog.vb

1. Public Class ColorDialog  
2.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
3.         ColorDialog1.FullOpen = True  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

4.         If ColorDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then  
5.             RichTextBox1.ForeColor = ColorDialog1.Color  
6.             RichTextBox1.BackColor = ColorDialog1.Color  
7.         End If  
8.     End Sub  
9.     Private Sub ColorDialog_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
10.         Me.Text = "javatpoint.com" 'set the title for the Windows form  
11.         Button1.Text = "Change TextBox Color"  
12.         Button2.Text = "Change Form Color"  
13.         Button3.Text = "Change Label Color"  
14.     End Sub  
15.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
16.         ColorDialog1.FullOpen = False  
17.         If ColorDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then  
18.             Me.BackColor = ColorDialog1.Color 'Change Background color of the form  
19.         End If  
20.     End Sub  
21.     Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click  
22.         ColorDialog1.FullOpen = True  
23.         If ColorDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then  
24.             Label1.ForeColor = ColorDialog1.Color 'set the color of the Label  
25.         End If  
26.     End Sub  
27. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
When we click on the any of the three buttons, it opens the Color popup window, as shown below.

Click the OK button to display the colored Windows Form, as shown below.

VB.NET Font Dialog Box


The Font Dialog Box allows the user to select the font family, style, and size for the text in an application.
However, a user can also select the font color and apply the current setting to the selected text of the
control by clicking the Apply button.

Let's create a Font Dialog box in the VB.NET Windows form using the following steps.

Step 1. We need to drag the Font Dialog box from the toolbox and drop it to the Windows form, as shown
below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step2: Once the Font Dialog is added to the form, we can set various properties of the Font by clicking on
the Font Dialog box.

Properties of Font Dialog


There are following properties of the Font Dialog Box in the VB.NET.

Properties Description

ShowApply The ShowApply property sets a value representing whether you want to display
the Apply button on the dialog box.

ShowEffects The ShowEffects property is used to set various effects on the text such as
strikethrough, text color, and underline options by setting values on the
FontDialog box.

Font The Font property is used to get or set the selected font to display changes.

Container The Container property is used to get the IContainer that contains the
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Component of the Font Dialog Box.

AllowVerticalFonts The AllowverticalFonts property is used to set or get a value that represents
whether the Font dialog box displays the horizontal and vertical fonts or
displays only horizontals fonts.

AllowScriptChange The AllowScriptChange property is used to set a value that allows the user to
change the character specified in the Script combo box to show a character set
other than the currently displayed character.

ScriptOnly The ScriptOnly property is used to set a value that allows the user to select only
the font, the character set of the symbol, and the ANSI character from the
dialog box.

ShowHelp The ShowHelp property is used to set a value representing whether the Help
button should be displayed in the dialog box.

MaxSize The MaxSize property gets or sets a value that allows the user to select only the
maximum point size character.

Options It is used to initialize FontDialog by obtaining values.

Methods of Font Dialog

Method Description

Equals() The Equals() method is used to check whether the current or defined object is the
same.

OnHelpRequest() It is used to call the HelpRequest event in the dialog box.

Reset() The Reset() method is used to reset all changes to their default values.

Dispose() The Dispose() method is used to free all resources used by the Control or the
component in the Dialog Box.

RunDialog() It is used to override a derived class to create a common dialog box.

ShowDialog() The ShowDialog () method is used to run a common dialog box with the default
setting.

CreateObjRef() The CreateObjRef () method is used to create an object that contains all related
information to initialize a proxy that can communicate with a remote object.

Events of Font Dialog

Events Description
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Disposed When control or component is terminated by calling the Dispose() method, a Dispose
event occurs.

HelpRequest When a user clicks the Help button of the dialog box, the HelpRequest event is called.

Apply When a user clicks on the Apply button of the Font dialog box, an apply event occurs.

Let's create a simple program to display the Font dialog box in the VB.NET Windows Forms.

FontDialog.vb

1. Public Class FontDialog  
2.     Private Sub FontDialog_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javaTpoint.com" 'set the title name for the Windows form.  
4.         Button1.Text = "Change Font" 'Set the name of button1  
5.         Button2.Text = "Exit" 'name of button2  
6.         Label1.Text = "Uses of Font"  
7.     End Sub  
8.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
9.         FontDialog1.ShowColor = True  
10.         If FontDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then  
11.             TextBox1.Font = FontDialog1.Font 'Change the font of the selected string  
12.             TextBox1.ForeColor = FontDialog1.Color 'Change the color of selected string  
13.         End If  
14.     End Sub  
15.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
16.         Me.Dispose() 'Terminate the program  
17.     End Sub  
18. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Write some text in TextArea, as shown below.

Select the string and click the 'Change Font' button; it opens the Font window. In the Font window, we can
change the size, font, and font style of the selected string.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

After setting the font, font style, size, and color, etc. on the Font dialog box, it shows the formatted string,
as shown below.

VB.NET Print Dialog Box


It is used to display the PrintDialog box in an application. It is an important dialog control that allows the
user to select sections of a document and then select a printer to print pages from the Windows Forms
application. Furthermore, a user can specify the range of pages to print, printer to use, number of copies in
the PrintDialog box. And we can display the PrintDialog control in a Windows form using
the ShowDialog() method.

Let's create a PrintDialog control in the VB.NET Windows form using the following steps.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Step 1: We have to find the PrintDialog, PrintDocument, PrintPreviewDialog control from the toolbox.
Drag and drop the PrintDialog, PrintDocument, PrintPreviewDialog control onto the window form, as
shown below.

Step 2: Once the Dialog is added to the form, we can set various properties of the PrintDialog by clicking
on the PrintDialog, PrintDocument, PrintPreviewDialog control.

Print Dialog Properties


There are following properties of the Print Dialog Dialog Box.

Properties Description

AllowPrintToFile The AllowPrintToFile property is used to set a value in the control box
representing whether the Print to File checkbox is enabled in the dialog box.

Document The Document property is used to set a value in the dialog box representing
whether the PrintDocument is capable of receiving PrintSettings.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

AllowCurrentPage The AllowCurrentPage property is used to set a value representing whether the
Current Page option button is displayed in the PrintDialog box.

PrintToFile The PrintToFile property is used to set or get a value in the control that
represents whether the Print to File checkbox is selected in the dialog box.

ShowHelp The ShowHelp property is used to set a value that represents whether the Help
button should be displayed in the dialog box.

PrinterSetting It is used to set the printer setting property in the PrintDialog box.

AllowSelection The AllowSelection property is used to set a value in the control that represents
whether the Selection option button is enabled in the PrintDialog box.

Methods of Print Dialog Control

Method Description

ShowDialog( The ShowDialog () method is used to run a common dialog box with the default
) setting.

Reset() The Reset() method is used to reset all changes to their default values.

Dispose() The Dispose() method is used to free all resources used by the Control or component
in the Dialog Box.

RunDialog() It is used to override a derived class to create a common dialog box.

Events of PrintDialog Control

Events Description

Disposed When control or component is terminated by calling the Dispose() method, a Dispose
event occurs.

HelpRequest When a user clicks the Help button of the dialog box, the HelpRequest event is called.

Let's create a simple program to print and preview the document in the VB.NET Windows Forms.

Printbox.vb

1. Public Class Printbox  
2.     Private Sub Printbox_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javatPoint.com" 'Set the title for the Windows form  
4.         Button1.Text = "Print"  
5.         Button2.Text = "Print Preview"  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

6.         Button1.BackColor = Color.SkyBlue  
7.         Button2.BackColor = Color.SkyBlue  
8.         PrintPreviewDialog1.Document = PrintDocument1  
9.     End Sub  
10.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
11.         If PrintDialog1.ShowDialog = DialogResult.OK Then 'Open the print dialog box  
12.             PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings  
13.             PrintDocument1.Print() 'print a document  
14.         End If  
15.     End Sub  
16.     Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles Prin
tDocument1.PrintPage  
17.         Dim font As New Font("Times New Roman", 24, FontStyle.Bold) 'set the font to display  
18.         e.Graphics.DrawString(RichTextBox1.Text, font, Brushes.Red, 100, 100) 'The DrawString() function is us
ed to print letters.  
19.     End Sub  
20.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
21.         If RichTextBox1.Text = " " Then  
22.             MsgBox("Please write some text...")  
23.         Else  
24.             PrintPreviewDialog1.ShowDialog()  
25.         End If  
26.     End Sub  
27. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Write some text in the textbox. We have written the following text in the text box, as shown below.

After writing the text, click the Print button to print the document and set printer settings, as shown below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Even we can check the preview of the document by clicking on the Print Preview button; it shows the
below image.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Dynamic Controls in VB.NET


Dynamic controls are the controls that are created dynamically, such as buttons, labels, textboxes, Radio
buttons, etc. at run time in the Windows forms. Each control of the VB.NET Toolbox is a member of the
Control class in the System.Windows.Forms namespace. And each control in the Toolbox is a class that is
similar to a Windows Forms class.

Methods of Dynamic Control


Add(): In Dynamic Control, we use the Add() method to add a new element to the current Form of the
control collection.

Syntax:

1. Controls.Add(controlObj)  

Remove(): The Remove method is used to remove an element from the control collection. It takes control'
object as an argument to be removed from the index of the control.

Syntax:

1. Controls.Remove(controlObj)  

Clear() Method: The Clear method is used to remove all elements of the controls from the Controls array
or clear the form.

Count Property: The Count property is used to count the number of dynamic controls as an element in a
control collection.

All() Method: All method is used to get all dynamic controls from the Windows Form as an array of
SystemWinForms.Control.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
Let's create a simple program to generate Dynamic control in the VB.NET Windows Forms.

DynamicControl.vb

1. Public Class DynamicControl  
2.     Private Sub DynamicControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javatpooint.com" 'Set the title for a Windows FOrm  
4.         Me.BackColor = Color.SkyBlue 'Set the background color of the Window form  
5.         Button1.Text = "Dynamic Button"  
6.         Button2.Text = "Dynamic TextBox"  
7.         Button3.Text = "Dynamic Label"  
8.         Button1.Font = New Font("Times New Roman", 12)  
9.         Button1.BackColor = Color.Red  
10.         Button2.BackColor = Color.Green  
11.         Button2.Font = New Font("Times New Roman", 12)  
12.         Button3.BackColor = Color.Violet  
13.         Button3.Font = New Font("Times New Roman", 12)  
14.     End Sub  
15.     Dim p As Integer = 1  
16.     Dim q As Integer = 1  
17.     Dim r As Integer = 1  
18.     Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button
3.Click  
19.         Dim label As New System.Windows.Forms.Label()  ' It is used to create label at run time  
20.         Me.Controls.Add(label) ' Add() method is used to Add Label  
21.         label.Top = r * 40  
22.         label.Left = 600  
23.         label.Text = "Label " & Me.r.ToString  
24.         label.Font = New Font("Times New Roman", 12) 'Set the font style of the label   
25.         r = r + 1  ' Add the Label one by one   
26.         MsgBox("You have successfully created a Label.")  
27.     End Sub  
28.     Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button
2.Click  
29.         Dim Txtbox As New System.Windows.Forms.TextBox()  ' It is used to create TextBox at run time  
30.         Me.Controls.Add(Txtbox)  ' Add() method is used to Add TextBox.  
31.         Txtbox.Top = q * 40  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

32.         Txtbox.Left = 340  
33.         Txtbox.Text = "TextBox " & Me.q.ToString  
34.         Txtbox.Font = New Font("Times New Roman", 12)  
35.         q = q + 1  
36.         MsgBox("You have successfully created a TextBox.")  
37.     End Sub  
38.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button
1.Click  
39.         Dim button As New System.Windows.Forms.Button()  ' It is used to create button at run time  
40.         Me.Controls.Add(button)  ' Add() method is used to Add button.   
41.         button.Top = p * 40  
42.         button.Left = 100  
43.         button.Text = "Button " & Me.p.ToString  
44.         button.Font = New Font("Times New Roman", 12)  
45.         p = p + 1  
46.         MsgBox("You have successfully created a button.")  
47.     End Sub  
48. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

At each click on the Dynamic Button, it shows the following message on the screen and creates a button in
the Windows Form at runtime, as shown below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

At each click on the Dynamic TextBox button, it shows the following message on the screen and creates a
TextBox in the Windows Form at runtime, as shown below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

At each click on the Dynamic Label button, it shows the following message on the screen and creates a
Label in the Windows Form at runtime, as shown below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

VB.NET Timer Control


The timer control is a looping control used to repeat any task in a given time interval. It is an important
control used in Client-side and Server-side programming, also in Windows Services.

Furthermore, if we want to execute an application after a specific amount of time, we can use the  Timer
Control. Once the timer is enabled, it generates a tick event handler to perform any defined task in its time
interval property. It starts when the start() method of timer control is called, and it repeats the defined task
continuously until the timer stops.

Let's create a Timer control in the VB.NET Windows form by using the following steps.

Step 1: Drag and drop the Timer control onto the window form, as shown below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Step 2: Once the Timer is added to the form, we can set various properties of the Timer by clicking on the
Timer control.

Timer Control Properties


There are following properties of the VB.NET Timer control.

Properties Description

Name The Name property is used to set the name of the control.

Enabled The Enables property is used to enable or disable the timer control. By default, it is
True.

Interval An Interval property is used to set or obtain the iteration interval in milliseconds to
raise the timer control's elapsed event. According to the interval, a timer repeats
the task.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

AutoReset The AutoReset property is used to obtain or set a Boolean value that determines
whether the timer raises the elapsed event only once.

Events Events property are used to get the list of event handler that is associated with
Event Component.

CanRaiseEvent It is used to get a value that represents whether the component can raise an event.
s

Events of Timer Control

Events Description

Dispose When control or component is terminated by calling the Dispose method, a Dispose event
d occurs.

Elapsed When the interval elapses in timer control, the Elapsed event has occurred.

Tick A tick event is used to repeat the task according to the time set in the Interval property. It
is the default event of a timer control that repeats the task between the Start() and Stop()
methods.

Methods of Timer Control

Methods Description

BeginInt() The BeginInt() method is used to start run time initialization of a timer control
used on a form or by another component.

Dispose() The Dispose() method is used to free all resources used by the Timer Control or
component.

Dispose(Boolean It is used to release all resources used by the current Timer control.
)

Close() The Close() method is used to release the resource used by the Timer Control.

Start() The Start() method is used to begin the Timer control's elapsed event by setting
the Enabled property to true.

EndInt() The EndInt() method is used to end the run time initialization of timer control that
is used on a form or by another component.

Stop() The Stop() method is used to stop the timer control's elapsed event by setting
Enabled property to false.

Let's create a simple program to understand the use of Timer Control in the VB.NET Windows Forms.

TimerProgram.vb
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

1. Public Class TimerProgram  
2.     Private Sub TimerProgram_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javatpooint.com" 'Set the title for a Windows Form  
4.         Label1.Text = "WELCOME TO JAVATPOINT.COM"  
5.         TextBox1.Text = 1  
6.         Timer1.Enabled = True  
7.         Button1.Text = "Start"  
8.         Button1.BackColor = Color.Green  
9.         Button1.ForeColor = Color.White  
10.         Button2.Text = "Stop"  
11.         Button2.BackColor = Color.Red  
12.         Button2.ForeColor = Color.White  
13.         Timer1.Start()  
14.         Timer1.Interval = 600 'set the time interval  
15.     End Sub  
16.     Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick  
17.         If Label1.ForeColor = Color.Red Then  
18.             Label1.ForeColor = Color.Blue  
19.         ElseIf Label1.ForeColor = Color.Blue Then  
20.             Label1.ForeColor = Color.Red  
21.         End If  
22.         TextBox1.Text = TextBox1.Text + 1 'Incremenet the TextBox1 by 1  
23.     End Sub  
24.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
25.         Timer1.Stop() ' Stop the timer  
26.     End Sub  
27.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
28.         Timer1.Start() 'Start the timer  
29.     End Sub  
30. End Class  

Output:
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

When the program executes, it starts blinking the WELCOME TO JAVATPOINT.COM statement and


counting the number to 1, as shown above. When the number is odd, the color of the statement is  Red,
and when the number is even, the color of the statement is Blue, as shown below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

How to keep a Form on top of others in VB.NET?


When we create a Windows application, we want to keep the main form on top of another form. We can
also say that when the application starts, a popup window form is displayed on top of the main form within
the application to start the further process. In VB6 we can see a Win32API that call SetWindowPos to set
the form always on top. And in VB.NET, it is simple to keep a form at the top using the TopMost property
of the form as True. After setting the TopMost property to true, the Uppermost form of a Windows
application that overlaps all other forms, even if the Uppermost form is not in the active or foreground
form.

Furthermore, the TopMost property of the form will force the form to the top layer of the screen when the
value of TopMost is true. And the Show() method is used to display the form in Windows Application.

The following syntax is used to set the form on top of others.

1. Dim f As New Form2  
2. f.TopMost = True  
3. f.Show()  

If we want to display a form on top of another form, we have to create two Windows Forms.

1. MainPage.vb
2. TopForm.vb

To keep the TopForm.vb Form on top of the MainPage.vb Form, we need to set the TopMost property in


the MainPage.vb file to True.

MainPage.vb

1. Public Class MainPage  
2.     Private Sub MainPage_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
3.         Me.Text = "javatpoint.com" 'Set the title for a Window Form   
4.         Label1.Text = "Student Name"  
5.         Label2.Text = "Roll No."  
6.         Button1.Font = New Font("Microsoft Sans Serif", 12)  
7.         Label3.Text = "Email ID"  
8.         Button1.Font = New Font("Microsoft Sans Serif", 12)  
9.         Label4.Text = "Course"  
10.         Button1.Font = New Font("Microsoft Sans Serif", 12)  
11.         Label5.Text = "Geder"  
12.         Button1.Font = New Font("Microsoft Sans Serif", 12)  
13.         Label6.Text = "Student Registration Details"  
14.         Label6.Font = New Font("Microsoft Sans Serif", 20)  ' Set Font style  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

15.         Label6.ForeColor = Color.Red  
16.         RadioButton1.Text = "Male"  ' Set the radiobutton1 and radiobutton2  
17.         RadioButton2.Text = "Female"  
18.         Button1.Text = "Submit"  
19.         Button1.Font = New Font("Microsoft Sans Serif", 10)  
20.         Button1.BackColor = Color.Green  
21.         ' Define the parameter to set the TopForm on top of the MainPage Form.  
22.         Dim frm As New TopForm  
23.         frm.TopMost = True 'Set the TopMost property to True  
24.         frm.Show() 'Show() method is used to display the TopForm  
25.     End Sub  
26.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
27.         Dim name As String  
28.         Dim rollno As String  
29.         Dim email As String  
30.         Dim course As String  
31.         Dim gen As String  
32.         name = TextBox1.Text  
33.         rollno = TextBox2.Text  
34.         email = TextBox3.Text  
35.         course = TextBox4.Text  
36.         If RadioButton1.Checked = True Then  
37.             gen = "Male"  
38.         ElseIf RadioButton2.Checked = True Then  
39.             gen = "Female"  
40.         End If  
41.         ' Display the user details, when the Button1 is clicked  
42.         MsgBox(" Your Name: " & name + vbCrLf + "Your Roll No: " & rollno + vbCrLf +  
43.                "Your Email: " & email + vbCrLf + "Your Course: " & course + vbCrLf + "Your Course: " & gen)  
44.     End Sub  
45. End Class  

TopForm.vb

1. Public Class TopForm  
2.     Private Sub TopForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

3.   
4.         PictureBox1.BackgroundImage = Image.FromFile("C:\Users\AMIT YADAV\Desktop\JTP.png")  
5.         PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage  
6.     End Sub  
7. End Class  

Output:

In the above image, the TopForm is placed at the top of the 'javatppoint.com' (MainPage). If we close
the TopForm, it shows the form, shown below.
VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE

Provide the detail in the Student Registration form and click on the Submit button.


VB.NET TUTORIALS BY FECKOUNDO TCHINDA FABRICE
After Clicking on the Submit button, it shows a popup message on the top of the MainPage.vb file
or javatpoint.com Form.

You might also like