VB Unit - 2
VB 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.
Sub Main()
End Sub
End Module
Let's compile and run the above program by pressing the F5 key, we get the follwoiing output.
Output:
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 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
b=1
n = 1234567
si = 0.12345678901234566
d = 0.12345678901234566
da = Today
c = "U"c
s = "Me"
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
'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
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
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:
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.
MinimizeBox MinimizeBox It is used to display the minimum option on the title bar of
the 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.
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.
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.
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.
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.
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.
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
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:
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.
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.
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
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.
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.
Click A Click event is found in the button control when the control is clicked.
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
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
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.