0% found this document useful (0 votes)
17 views41 pages

VB Unit - 2

VB.NET is a multi-paradigm, object-oriented programming language developed by Microsoft for creating a variety of applications on the .NET Framework. It supports key OOP concepts, is not case-sensitive, and allows for rapid application development with features such as multithreading and automatic garbage collection. The document also covers the advantages and disadvantages of VB.NET, its environment setup, data types, and provides examples of basic program structure and execution.

Uploaded by

sumaiya10601
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views41 pages

VB Unit - 2

VB.NET is a multi-paradigm, object-oriented programming language developed by Microsoft for creating a variety of applications on the .NET Framework. It supports key OOP concepts, is not case-sensitive, and allows for rapid application development with features such as multithreading and automatic garbage collection. The document also covers the advantages and disadvantages of VB.NET, its environment setup, data types, and provides examples of basic program structure and execution.

Uploaded by

sumaiya10601
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Unit - 2

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

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

VB.Net - Environment Setup


The .Net Framework
The .Net framework is a revolutionary platform that helps you to write the following types of applications

• Windows applications
• Web applications
• Web services
The .Net framework applications are multi-platform applications. The framework has been designed in
such a way that it can be used from any of the following languages: Visual Basic, C#, C++, Jscript, and
COBOL, etc.
All these languages can access the framework as well as communicate with each other.
The .Net framework consists of an enormous library of codes used by the client languages like VB.Net.
These languages use object-oriented methodology.
Following are some of the components of the .Net framework −
• Common Language Runtime (CLR)
• The .Net Framework Class Library
• Common Language Specification
• Common Type System
• Metadata and Assemblies
• Windows Forms
• ASP.Net and ASP.Net AJAX
• ADO.Net
• Windows Workflow Foundation (WF)
• Windows Presentation Foundation
• Windows Communication Foundation (WCF)
• LINQ
For the jobs each of these components perform, please see ASP.Net - Introduction, and for details of each
component, please consult Microsoft's documentation.
Integrated Development Environment (IDE) For VB.Net
Microsoft provides the following development tools for VB.Net programming −
• Visual Studio 2010 (VS)
• Visual Basic 2010 Express (VBE)
• Visual Web Developer
The last two are free. Using these tools, you can write all kinds of VB.Net programs from simple
command-line applications to more complex applications. Visual Basic Express and Visual Web
Developer Express edition are trimmed down versions of Visual Studio and has the same look and feel.
They retain most features of Visual Studio. In this tutorial, we have used Visual Basic 2010 Express and
Visual Web Developer (for the web programming chapter).
You can download it from here. It gets automatically installed in your machine. Please note that you need
an active internet connection for installing the express edition.

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

Imports System 'System is a Namespace


Module Hello_Program

Sub Main()

Console.WriteLine("Hello, Welcome to the world of VB.NET")


Console.WriteLine("Press any key to continue...")
Console.ReadKey()

End Sub

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.

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

Step 4: Provide the Project name and location to store the project file using the browse button in Location.

Step 5: Click on the Create button. The following window appears on the screen.
Step 6: Now double click on the middle area of Form1.vb (Design) file, it shows the following code.

Form1.vb
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MsgBox("Welcome to the JavaTpoint")
End Sub
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 - Data Types
Data types refer to an extensive system used for declaring variables or functions of different types. The
type of a variable determines how much space it occupies in storage and how the bit pattern stored is
interpreted.
Data Types Available in VB.Net
VB.Net provides a wide range of data types. The following table shows all the data types available −
Data Type Storage Allocation Value Range
Boolean Depends on implementing True or False
platform
Byte 1 byte 0 through 255 (unsigned)
Char 2 bytes 0 through 65535 (unsigned)
Date 8 bytes 0:00:00 (midnight) on January 1, 0001 through
11:59:59 PM on December 31, 9999

Decimal 16 bytes 0 through +/-


79,228,162,514,264,337,593,543,950,335 (+/-
7.9...E+28) with no decimal point; 0 through +/-
7.9228162514264337593543950335 with 28 places
to the right of the decimal

Double 8 bytes -1.79769313486231570E+308 through -


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

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

Long 8 bytes -9,223,372,036,854,775,808 through


9,223,372,036,854,775,807(signed)
Object 4 bytes on 32-bit platform Any type can be stored in a variable of type Object
8 bytes on 64-bit platform

SByte 1 byte -128 through 127 (signed)


Short 2 bytes -32,768 through 32,767 (signed)
Single 4 bytes -3.4028235E+38 through -1.401298E-45 for
negative values;
1.401298E-45 through 3.4028235E+38 for positive
values
String Depends on implementing 0 to approximately 2 billion Unicode characters
platform
UInteger 4 bytes 0 through 4,294,967,295 (unsigned)
ULong 8 bytes 0 through 18,446,744,073,709,551,615 (unsigned)
User-Defined Depends on implementing Each member of the structure has a range
platform determined by its data type and independent of the
ranges of the other members
UShort 2 bytes 0 through 65,535 (unsigned)
Example
The following example demonstrates use of some of the types −
Module DataTypes
Sub Main()
Dim b As Byte
Dim n As Integer
Dim si As Single
Dim d As Double
Dim da As Date
Dim c As Char
Dim s As String
Dim bl As Boolean

b=1
n = 1234567
si = 0.12345678901234566
d = 0.12345678901234566
da = Today
c = "U"c
s = "Me"

If ScriptEngine = "VB" Then


bl = True
Else
bl = False
End If

If bl Then
'the oath taking
Console.Write(c & " and," & s & vbCrLf)
Console.WriteLine("declaring on the day of: {0}", da)
Console.WriteLine("We will learn VB.Net seriously")
Console.WriteLine("Lets see what happens to the floating point variables:")
Console.WriteLine("The Single: {0}, The Double: {1}", si, d)
End If
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
U and, Me
declaring on the day of: 12/4/2012 12:00:00 PM
We will learn VB.Net seriously
Lets see what happens to the floating point variables:
The Single:0.1234568, The Double: 0.123456789012346
The Type Conversion Functions in VB.Net
VB.Net provides the following in-line type conversion functions −
Sr.No. Functions & Description
1 CBool(expression)
Converts the expression to Boolean data type.

2 CByte(expression)
Converts the expression to Byte data type.
3 CChar(expression)
Converts the expression to Char data type.

4 CDate(expression)
Converts the expression to Date data type
5 CDbl(expression)
Converts the expression to Double data type.
6 CDec(expression)
Converts the expression to Decimal data type.

7 CInt(expression)
Converts the expression to Integer data type.

8 CLng(expression)
Converts the expression to Long data type.
9 CObj(expression)
Converts the expression to Object type.

10 CSByte(expression)
Converts the expression to SByte data type.

11 CShort(expression)
Converts the expression to Short data type.
12 CSng(expression)
Converts the expression to Single data type.
13 CStr(expression)
Converts the expression to String data type.

14 CUInt(expression)
Converts the expression to UInt data type.

15 CULng(expression)
Converts the expression to ULng data type.

16 CUShort(expression)
Converts the expression to UShort data type.
Example
The following example demonstrates some of these functions −

Module DataTypes
Sub Main()
Dim n As Integer
Dim da As Date
Dim bl As Boolean = True
n = 1234567
da = Today

Console.WriteLine(bl)
Console.WriteLine(CSByte(bl))
Console.WriteLine(CStr(bl))
Console.WriteLine(CStr(da))
Console.WriteLine(CChar(CChar(CStr(n))))
Console.WriteLine(CChar(CStr(da)))
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
True
-1
True
12/4/2012
1
1
VB.Net - Sub Procedures
As we mentioned in the previous chapter, Sub procedures are procedures that do not return any value. We
have been using the Sub procedure Main in all our examples. We have been writing console applications
so far in these tutorials. When these applications start, the control goes to the Main Sub procedure, and it
in turn, runs any other statements constituting the body of the program.
Defining Sub Procedures
The Sub statement is used to declare the name, parameter and the body of a sub procedure. The syntax for
the Sub statement is −
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
• Modifiers − specify the access level of the procedure; possible values are - Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing,
and shadowing.
• SubName − indicates the name of the Sub
• ParameterList − specifies the list of the parameters
Example
The following example demonstrates a Sub procedure CalculatePay that takes two
parameters hours and wages and displays the total pay of an employee −
Live Demo
Module mysub
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
CalculatePay(25, 10)
CalculatePay(40, 20)
CalculatePay(30, 27.5)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Total Pay: $250.00
Total Pay: $800.00
Total Pay: $825.00
Passing Parameters by Value
This is the default mechanism for passing parameters to a method. In this mechanism, when a method is
called, a new storage location is created for each value parameter. The values of the actual parameters are
copied into them. So, the changes made to the parameter inside the method have no effect on the
argument.
In VB.Net, you declare the reference parameters using the ByVal keyword. The following example
demonstrates the concept −

Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there is no change in the values though they had been changed inside the function.
Passing Parameters by Reference
A reference parameter is a reference to a memory location of a variable. When you pass parameters by
reference, unlike value parameters, a new storage location is not created for these parameters. The
reference parameters represent the same memory location as the actual parameters that are supplied to the
method.
In VB.Net, you declare the reference parameters using the ByRef keyword. The following example
demonstrates this −

Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

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
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.
[ Access_Specifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] Class ClassName
' Data Members or Variable Declaration
' Methods Name
' Statement to be executed
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
Public Class My_program
' properties, method name, etc
' Statement to be executed
End Class
In the above syntax, we have created a class with the name 'My_program' using the Class keyword.
The Syntax for creating an object
Dim Obj_Name As Class_Name = New Class_Name() ' Declaration of object
Obj_Name.Method_Name() ' Access a method using the object
In the above syntax, we have created an instance (Obj_Name) for the class Class_Name. By using the
object name 'Obj_Name' to access all the data members and the method name of Class_Name.
Let's create a program to find the Area and Parameter of a rectangle using the class and object in VB.NET.
My_program.vb
Imports System
Module My_program
Sub Main()
Dim rect As Rectangle = New Rectangle() 'create an object
Dim rect2 As Rectangle = New Rectangle() 'create an object
Dim area, para As Integer

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

'rect2 specification
rect2.setLength = (5)
rect2.setBreadth = (10)

'Area of rectangle
area = rect.length * rect.Breadth
'area = rect.GetArea()
Console.WriteLine(" Area of Rectangle is {0}", area)

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

Public Sub setLength(ByVal len As Integer)


length = len
End Sub

Public Sub setBreadth(ByVal bre As Integer)


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

Public Function GetParameter() As Integer


Return 2 * (length + Breadth)
End Function
End Class
End Module
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
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.
Public Class MyClass
' Creates a Constructor using the New
Public Sub New()
'Statement to be executed
End Sub
End Class
Let's create a program to define the default constructor in a VB.NET programming language.
Default_Const.vb
Imports System
Module Default_Const
Class Tutor
Public name As String
Public topic As String
' Create a default constructor
Public Sub New()
name = "JavaTpoint"
topic = "VB.NET Tutorial"
End Sub
End Class
Sub Main()
' The constructor will automatically call when the instance of the class is created
Dim tutor As Tutor = New Tutor() ' Create an object as a tutor
Console.WriteLine(" Your Site Name is : {0}", tutor.name)
Console.WriteLine(" Your Topic Name is : {0}", tutor.topic)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
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
Imports System
Module Para_Const
Class Tutor
Public name As String
Public topic As String
' Create a parameterized constructor to pass parameter
Public Sub New(ByVal a As String, ByVal b As String)
name = a
topic = b
Console.WriteLine(" We are using a parameterized constructor to pass the parameter")
End Sub
End Class
Sub Main()
' The constructor will automatically call when the instance of the class is created
Dim tutor As Tutor = New Tutor("JavaTpoint", "VB.NET Constructor")
Console.WriteLine(" Your Site Name is : {0}", tutor.name)
Console.WriteLine(" Your Topic Name is : {0}", tutor.topic)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
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.
Class My_Destructor
' define the destructor
Protected Overrides Sub Finalize()
' Statement or code to be executed
End Sub
End Class
Let's create a program to use the Finalize() method in VB.NET Destructor.
Destruct.vb
Imports System
Module Destruct
Class Get_Destroy
Public Sub New()
Console.WriteLine(" An Object of the class is being created")
End Sub
' Use Finalize() method of Destructor
Protected Overrides Sub Finalize()
Console.WriteLine(" An Object of the class is being destroyed")
Console.WriteLine(" Press any key to exit")
End Sub
End Class

Sub Main()
Get_Details() ' After invoking the Get_Details() method, garbage collector is called automatically
GC.Collect()
Console.ReadKey()
End Sub
Public Sub Get_Details()
Dim dest As Get_Destroy = New Get_Destroy()
End Sub
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
Imports System
Module Const_Over
Class Details
Public name As String
Public course As String
' Define Default Constructor
Public Sub New()
name = "Prince"
course = "Coputer Science"
Console.WriteLine(" Uses of Overloading Constructor")
End Sub
' Create a parametrized constructor
Public Sub New(ByVal a As String, ByVal b As String)
name = a
course = b
End Sub
End Class
Sub Main()
' Called default constructor
Dim det As Details = New Details()
' Called the parametrized constructor
Dim det1 As Details = New Details("Peter", "Knowledge of Data Mining")
Console.WriteLine(" Your Details are: Name : {0} and Course : {1}", det.name, det.course)
Console.WriteLine(" Your Overloaded Details are: Name : {0} and Course :{1}", det1.name, det1.co
urse)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
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.
<access_modifier> Class <Name_of_baseClass>
' Implementation of base class
End Class
<access_modifier> Class <Name_of_derivedClass>
Inherits Name_of_baseClass
' Implementation of derived class
End Class
Let's create a program to understand the concept of Inheritance in VB.NET
Simple_Inherit.vb
Imports System
Module Simple_Inherit
Public Class Vehicle
Public Sub speed()
Console.WriteLine(" 4 Wheeler cars are more luxurious than 2 Wheeler")
End Sub

Public Overridable Sub perform()


Console.WriteLine(" Both Vehicles are good, but in a narrow lane, two-
wheeler are more comfortable than 4-Wheeler")
End Sub
End Class

Class Bike
Inherits Vehicle
Public Overrides Sub perform()
Console.WriteLine(" Two-wheeler are lesser weight as compared to 4 wheeler")
End Sub
End Class
Class Car
Inherits Vehicle
Public Overrides Sub perform()
Console.WriteLine(" It is 4 wheelar car")
End Sub
End Class

Sub Main()
Dim vehicle As Vehicle = New Vehicle()
Dim bike As Bike = New Bike()
Dim car As Car = New Car()
vehicle = bike
vehicle.perform()
vehicle = car
vehicle.perform()
Console.WriteLine(" Press any ley to exit...")
Console.ReadKey()
End Sub
End Module
Output:
Let's create a program of inheritance using the MyBase in VB.NET.
Inherit_class.vb
Module Inherit_class
Class Circle 'base class
Protected radius As Integer
Public Const PI As Double = 3.14
Public Sub New(ByVal r As Integer)
radius = r
End Sub
Public Function GetAreaCircle() As Double
Return (PI * radius * radius)
End Function
Public Overridable Sub Show()
Console.WriteLine(" Radius of circle : {0}", radius)
Console.WriteLine(" Area of circle is {0}", GetAreaCircle())
End Sub
End Class

'Derived Class
Class MyDeriveClass : Inherits Circle
Private dimen As Double
Public Sub New(ByVal r As Integer)
MyBase.New(r)
End Sub
Public Function Getdimen() As Double
Dim dimen As Double
dimen = GetArea() * 50
Return dimen
End Function
Public Overrides Sub Show()
MyBase.Show()
Console.WriteLine("Total Cost: {0}", Getdimen())
End Sub
End Class

Class Circle_Class
Shared Sub Main()
Dim c As MyDeriveClass = New MyDeriveClass(5)
c.Show()
Console.WriteLine("Press any key to exit")
Console.ReadKey()
End Sub
End Class
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 member of both class B and Class A. The process of extending one class to another
is known as multilevel inheritance.
Public Class A
' implementation of code
End Class

Public Class B
Inherits A
' Implementation of Code
End Class

Public Class C
Inherits A
' Implementation of code
End Class
Let's create a program to understand the concept of Multi-Level Inheritance in VB.NET
Multi_inherit1.vb
Module Multi_inherit1
Public Class A
Public SName As String
Public Sub Display()
Console.WriteLine(" Name of Student : {0}", SName)
End Sub
End Class
Public Class B
Inherits A
Public place As String
Public Sub GetPlace()
Console.WriteLine(" Address : {0}", place)
End Sub
End Class

Public Class C
Inherits B
Public rollno As Integer
Public Sub GetRollno()
Console.WriteLine(" Student Roll no. {0}", rollno)
End Sub
End Class

Class Profile
Public Sub Main(ByVal args As String())
Dim c As C = New C()
c.SName = "Donald Trump"
c.place = "USA"
c.rollno = 102
c.Display()
c.GetPlace()
c.GetRollno()
Console.WriteLine(" Press any key to exit")
Console.ReadKey()
End Sub
End Class
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.
Class MyClass
Inherits IClass
Private Sub FetchDetails() Implements IClass.FetchDetails
' Method Implementation
End Sub
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
Module Get_Interface
Interface IStudent
Sub Details(ByVal y As String)
End Interface
Class Student
Implements IStudent
Public Sub Details(ByVal a As String) Implements IStudent.Details
' Throw New NotImplementedException()
Console.WriteLine(" Name of Student: {0}", a)
End Sub
End Class

Class Student1
Implements IStudent
Public Sub Details(ByVal a As String) Implements IStudent.Details
'Throw New NotImplementedException()
Console.WriteLine(" Course: {0}", a)
End Sub
End Class
Sub Main(ByVal args As String())
Dim stud As IStudent = New Student()
stud.Details(" James Watt")
Dim stud1 As IStudent = New Student1()
stud1.Details("Computer Science")
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:

VB.NET Form Controls


A Form is used in VB.NET to create a form-based or window-based application. Using the form, we can
build a attractive user interface. It is like a container for holding different control that allows the user to
interact with an application. The controls are an object in a form such as buttons,
Textboxes, Textarea, labels, etc. to perform some action. However, we can add any control to the runtime
by creating an instance of it.
A Form uses a System.Windows.Form namespace, and it has a wide family of controls that add both
forms and functions in a Window-based user interface.

VB.NET Form Properties


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

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

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

Cursor It is used to set the cursor image when it hovers over the form.
AllowDrop Using the AllowDrop control in a form, it allows whether to drag and
drop on the form.

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

Locked It determines whether the form is locked or not.

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

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

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

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


Document Interface (MDI) child form.

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

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

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

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

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

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

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

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

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

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

Form Events
The following are the most important list of events related to a form.
Events Description

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

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

Closed A closed event is found before closing the form.

Closing It exists when a form is closing.


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

DragDrop A DragDrop event is activated when a drag and drop operation is


performed.

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

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

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

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


the form.

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

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

LostFocus It is activated when the form loses focus.

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

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

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

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

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


code.

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

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

For creating a Windows Forms application in VB.NET, we need to follow the following steps in
Microsoft Visual Studio.
1. GoTo File Menu.
2. Click on New Project.
3. Click on Windows Forms App or Application
And finally, click on the 'Create' button to create your project, and then, it displays the following window
form with a name Form1.
Now create a simple program of Windows form control in VB.NET.
Form1.vb
Public Class Form1
' Create nameStr and num variables
Dim nameStr As String
Dim num As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub
' It is Label1
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click

End Sub
' It is TextBox1 for inserting the value.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChang
ed

End Sub
' It is Label2
Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click

End Sub

' It is a Button1 for transferring the control.


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
nameStr = TextBox1.Text
num = TextBox2.Text
Label3.Text = "You have entered the Name " & nameStr + " Number " & num
End Sub

' It is TextBox2 for inserting the value.


Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChang
ed

End Sub
' It is label3
Private Sub Label3_Click(sender As Object, e As EventArgs) Handles Label3.Click

End Sub
End Class
Output:
Enter the following details in the form:

After filling all the details, click on the Submit button.


After that, it shows the following Output:

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.
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
Public Class Dialog
Private Sub Dialog_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Button1.Text = "Click Me" 'Set the name of button
Me.Text = "javatpoint.com" ' Set the title name for the Windows Form
Button1.BackColor = Color.Green ' Background color of the button
End Sub

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


Dim result1 As DialogResult = MessageBox.Show("Is VB.NET programming language easy to learn
?",
"Important Question",
MessageBoxButtons.YesNo)
End Sub
End Class
Output:

Now, click on the Click Me button of the Windows Form, it displays


the dialog box, as shown below.

Tooltip Control In VB.NET


A tooltip is a small pop-up window that displays some information when you rollover on a control.

In this article, I will discuss how to create and use a Tooltip control in a Windows Forms application using
Visual Studio 2010. After that, I will discuss various properties and methods available for the Tooltip
control.
Creating a Tooltip
Tooltip class represents a tooltip control. Once a Tooltip object is created, we need to call SetToolTip
method and pass a control and text. The following code snippet creates a Tooltip and attach to a Button
control using SetToolTip method.
Dim toolTip1 As New ToolTip()
toolTip1.ShowAlways = True
toolTip1.SetToolTip(button1, "Click me to execute.")

If you rollover on Button control, you will see the following output.

Figure 1
Tooltip Properties
· Active - A tooltip is currently active.
· AutomaticDelay - Automatic delay for the tooltip.
· AutoPopDelay - The period of time the ToolTip remains visible if the pointer is stationary on a
control with specified ToolTip text.
InitialDelay - Gets or sets the time that passes before the ToolTip appears.
· IsBaloon - Gets or sets a value indicating whether the ToolTip should use a balloon window.
· ReshowDelay - Gets or sets the length of time that must transpire before subsequent ToolTip
windows appear as the pointer moves from one control to another.
· ShowAlways - Displays if tooltip is displayed even the parent control is not active.

The following code snippet sets some of these properties.


Dim buttonToolTip As New ToolTip()
buttonToolTip.ToolTipTitle = "Button Tooltip"
buttonToolTip.UseFading = True

buttonToolTip.UseAnimation = True
buttonToolTip.IsBalloon = True
buttonToolTip.ShowAlways = True
buttonToolTip.AutoPopDelay = 5000
buttonToolTip.InitialDelay = 1000
buttonToolTip.ReshowDelay = 500
buttonToolTip.IsBalloon = True
buttonToolTip.SetToolTip(Button1, "Click me to execute.")
Balloon Tooltip
By setting IsBalloon to true makes a tooltip balloon that looks like Figure 2.
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.

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

ShowItemToolTips It is used to obtain or set the value that determines if the ToolTips are displayed
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.

Now, we write the Shortcut keys for the File subitems, such as New -> Ctrl + N, Open -> Ctrl + O, etc.
After that, we can see the subitems of the Files with their Shortcut keys, as shown below.

Menus.vb
Public Class Menus
Private Sub Menus_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "javatpoint.com" 'set the title of the bar
BackColor = Color.SkyBlue
End Sub

Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripM


enuItem.Click
Me.Dispose() ' exit from the form
End Sub
End Class
Output:
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.
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.

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

When we click on the Menu item, it shows the following image on the screen.
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 Windows form by using the following steps:
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
BackColorChanged A BackColorChaged event is found in button control when the
Background property is changed.

BackgroundImageChanged A BackgoundImageChanged event is found in button control when the


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
Public Class Button_Control
Private Sub Button_Control_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Button1.Text = "Click Me" ' Set the name of button
End Sub

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


MsgBox(" Visit here: https://www.javatpoint.com")
' Display the message, when a user clicks on Click me button
End Sub
End Class
Output:
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
Public Class Button_Control
Private Sub Button_Control_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Button1.Text = "Submit" ' Set the name of button
Button2.Text = "Exit"
Button3.Text = "Show Image"
End Sub

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


MsgBox(" Visit here: https://www.javatpoint.com/vb-
net") ' Display the message, when a user click on Click me button
End Sub

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


End ' It is used for terminating the program.
End Sub

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


PictureBox1.Visible = True
End Sub

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click


End Sub
End Class
Output:

Now Click on the Click Me button, it shows the following message on the screen.

Now click on the Show Image button, it shows the following image on the screen.

Click on the Exit button to terminate the program.

You might also like