A procedure is a group of statements that together perform a task, when called. After the procedure is executed, the control returns to the statement calling the procedure. VB.Net has two types of procedures:
Functions
Sub procedures or Subs
Functions return a value, where Subs do not return a value.
Defining a Function
The Function statement is used to declare the name, parameter and the body of a function. The syntax for the Function statement is:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
Where,
Tutorial content goes here.....
Modifiers: specifiy the access level of the function; possible values are: Public, Private, Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.
FunctionName: indicates the name of the function
ParameterList: specifies the list of the parameters
ReturnType: specifies the data type of the variable the function returns
Example
Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two.
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num1 > num2) Then
result = num1
Else
result = num2
End If
FindMax = result
End Function
Function Returning a Value
In VB.Net a function can return a value to the calling code in two ways:
The following example demonstrates using the FindMax function:
Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num1 > num2) Then
result = num1
Else
result = num2
End If
FindMax = result
End Function
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200
Dim res As Integer
res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
Max value is : 200
Recursive Function
A function can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function:
Module myfunctions
Function factorial(ByVal num As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function
Sub Main()
'calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
Param Arrays
At times, while declaring a function or sub procedure you are not sure of the number of arguments passed as a parameter. VB.Net param arrays (or parameter arrays) come into help at these times.
The following example demonstrates this:
Module myparamfunc
Function AddElements(ParamArray arr As Integer()) As Integer
Dim sum As Integer = 0
Dim i As Integer = 0
For Each i In arr
sum += i
Next i
Return sum
End Function
Sub Main()
Dim sum As Integer
sum = AddElements(512, 720, 250, 567, 889)
Console.WriteLine("The sum is: {0}", sum)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
The sum is: 2938
Passing Arrays as Function Arguments
You can pass an array as a function argument in VB.Net. The following example demonstrates this:
Module arrayParameter
Function getAverage(ByVal arr As Integer(), ByVal size As Integer) As Double
'local variables
Dim i As Integer
Dim avg As Double
Dim sum As Integer = 0
For i = 0 To size - 1
sum += arr(i)
Next i
avg = sum / size
Return avg
End Function
Sub Main()
' an int array with 5 elements '
Dim balance As Integer() = {1000, 2, 3, 17, 50}
Dim avg As Double
'pass pointer to the array as an argument
avg = getAverage(balance, 5)
' output the returned value '
Console.WriteLine("Average value is: {0} ", avg)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
Average value is: 214.4
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: specifiy 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 wagesand displays the total pay of an employee:
Module mysub
Sub CalculatePay(ByVal hours As Double, ByVal 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 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 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 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
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.
Objects are instances of a class. The methods and variables that constitute a class are called members of the class.
Class Definition
A class definition starts with the keyword Class followed by the class name; and the class body, ended by the End Class statement. Following is the general form of a class definition:
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Where,
attributelist is a list of attributes that apply to the class. Optional.
accessmodifier defines the access levels of the class, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional.
Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional.
MustInherit specifies that the class can be used only as a base class and that you cannot create an object directly from it, i.e, an abstract class. Optional.
NotInheritable specifies that the class cannot be used as a base class.
Partial indicates a partial definition of the class
Inherits specifies the base class it is inheriting from
Implements specifies the interfaces the class is inheriting from
The following example demonstrates a Box class, with three data members, length, breadth and height:
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
' box 1 specification
Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0
' box 2 specification
Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0
'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Member Functions and Encapsulation
A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.
Member variables are attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.
Let us put above concepts to set and get the value of different class members in a class:
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Sub setBreadth(ByVal bre As Double)
breadth = bre
End Sub
Public Sub setHeight(ByVal hei As Double)
height = hei
End Sub
Public Function getVolume() As Double
Return length * breadth * height
End Function
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
' box 1 specification
Box1.setLength(6.0)
Box1.setBreadth(7.0)
Box1.setHeight(5.0)
'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)
' volume of box 1
volume = Box1.getVolume()
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = Box2.getVolume()
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Constructors and Destructors
A class constructor is a special member Sub of a class that is executed whenever we create new objects of that class. A constructor has the name New and it does not have any return type.
Following program explain the concept of constructor:
Class Line
Private length As Double ' Length of a line
Public Sub New() 'constructor
Console.WriteLine("Object is being created")
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Function getLength() As Double
Return length
End Function
Shared Sub Main()
Dim line As Line = New Line()
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces following result:
Object is being created
Length of line : 6
A default constructor does not have any parameter but if you need a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation as shown in the following example:
Class Line
Private length As Double ' Length of a line
Public Sub New(ByVal len As Double) 'parameterised constructor
Console.WriteLine("Object is being created, length = {0}", len)
length = len
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Function getLength() As Double
Return length
End Function
Shared Sub Main()
Dim line As Line = New Line(10.0)
Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces following result:
Object is being created, length = 10
Length of line set by constructor : 10
Length of line set by setLength : 6
A destructor is a special member Sub of a class that is executed whenever an object of its class goes out of scope.
A destructor has the name Finalize and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.
Destructors cannot be inherited or overloaded.
Following example explain the concept of destructor:
Class Line
Private length As Double ' Length of a line
Public Sub New() 'parameterised constructor
Console.WriteLine("Object is being created")
End Sub
Protected Overrides Sub Finalize() ' destructor
Console.WriteLine("Object is being deleted")
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Function getLength() As Double
Return length
End Function
Shared Sub Main()
Dim line As Line = New Line()
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces following result:
Object is being created
Length of line : 6
Object is being deleted
Shared Members of a VB.Net Class
We can define class members as static using the Shared keyword. When we declare a member of a class as Shared it means no matter how many objects of the class are created, there is only one copy of the member.
The keyword Shared implies that only one instance of the member exists for a class. Shared variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it.
Shared variables can be initialized outside the member function or class definition. You can also initialize Shared variables inside the class definition.
You can also declare a member function as Shared. Such functions can access only Shared variables. The Shared functions exist even before the object is created.
The following example demonstrates the use of shared members:
Class StaticVar
Public Shared num As Integer
Public Sub count()
num = num + 1
End Sub
Public Shared Function getNum() As Integer
Return num
End Function
Shared Sub Main()
Dim s As StaticVar = New StaticVar()
s.count()
s.count()
s.count()
Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces following result:
Value of variable num: 3
Inheritance
One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the baseclass, and the new class is referred to as the derived class.
Base & Derived Classes:
A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base class or interface.
The syntax used in VB.Net for creating derived classes is as follows:
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
Consider a base class Shape and its derived class Rectangle:
' Base class
Class Shape
Protected width As Integer
Protected height As Integer
Public Sub setWidth(ByVal w As Integer)
width = w
End Sub
Public Sub setHeight(ByVal h As Integer)
height = h
End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
Public Function getArea() As Integer
Return (width * height)
End Function
End Class
Class RectangleTester
Shared Sub Main()
Dim rect As Rectangle = New Rectangle()
rect.setWidth(5)
rect.setHeight(7)
' Print the area of the object.
Console.WriteLine("Total area: {0}", rect.getArea())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces following result:
Total area: 35
Base Class Initialization
The derived class inherits the base class member variables and member methods. Therefore the super class object should be created before the subclass is created. The super class or the base class is implicitly known as MyBasein VB.Net
The following program demonstrates this:
' Base class
Class Rectangle
Protected width As Double
Protected length As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
length = l
width = w
End Sub
Public Function GetArea() As Double
Return (width * length)
End Function
Public Overridable Sub Display()
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
End Sub
'end class Rectangle
End Class
'Derived class
Class Tabletop : Inherits Rectangle
Private cost As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
MyBase.New(l, w)
End Sub
Public Function GetCost() As Double
Dim cost As Double
cost = GetArea() * 70
Return cost
End Function
Public Overrides Sub Display()
MyBase.Display()
Console.WriteLine("Cost: {0}", GetCost())
End Sub
'end class Tabletop
End Class
Class RectangleTester
Shared Sub Main()
Dim t As Tabletop = New Tabletop(4.5, 7.5)
t.Display()
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces following result:
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5
VB.Net supports multiple inheritance.
An exception is a problem that arises during the execution of a program. An exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. VB.Net exception handling is built upon four keywords: Try, Catch, Finally and Throw.
Try: A Try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more Catch blocks.
Catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The Catch keyword indicates the catching of an exception.
Finally: The Finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
Throw: A program throws an exception when a problem shows up. This is done using a Throw keyword.
Syntax
Assuming a block will raise and exception, a method catches an exception using a combination of the Try and Catch keywords. A Try/Catch block is placed around the code that might generate an exception. Code within a Try/Catch block is referred to as protected code, and the syntax for using Try/Catch looks like the following:
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations.
Exception Classes in .Net Framework
In the .Net Framework exceptions are represented by classes. The exception classes in .Net Framework are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. So the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the Sytem.SystemException class:
| Exception Class | Description |
| System.IO.IOException | Handles I/O errors. |
| System.IndexOutOfRangeException | Handles errors generated when a method refers to an array index out of range. |
| System.ArrayTypeMismatchException | Handles errors generated when type is mismatched with the array type. |
| System.NullReferenceException | Handles errors generated from deferencing a null object. |
| System.DivideByZeroException | Handles errors generated from dividing a dividend with zero. |
| System.InvalidCastException | Handles errors generated during typecasting. |
| System.OutOfMemoryException | Handles errors generated from insufficient free memory. |
| System.StackOverflowException | Handles errors generated from stack overflow. |
Handling Exceptions
VB.Net provides a structured solution to the exception handling problems in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements.
These error handling blocks are implemented using the Try, Catch and Finally keywords. Following is an example of throwing an exception when dividing by zero condition occurs:
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0
Creating User-Defined Exceptions
You can also define your own exception. User defined exception classes are derived from theApplicationException class. The following example demonstrates this:
Module exceptionProg
Public Class TempIsZeroException : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Public Class Temperature
Dim temperature As Integer = 0
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If
End Sub
End Class
Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
TempIsZeroException: Zero Temperature found
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception class.
You can use a throw statement in the catch block to throw the present object as:
Throw [ expression ]
The following program demonstrates this:
Module exceptionProg
Sub Main()
Try
Throw New ApplicationException("A custom exception _
is being thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
A custom exception is being thrown here...
Now inside the Finally Block
A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream.
The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation).
VB.Net I/O Classes
The System.IO namespace has various class that are used for performing various operation with files, like creating and deleting files, reading from or writing to a file, closing a file etc.
The following table shows some commonly used non-abstract classes in the System.IO namespace:
| I/O Class | Description |
| BinaryReader | Reads primitive data from a binary stream. |
| BinaryWriter | Writes primitive data in binary format. |
| BufferedStream | A temporary storage for a stream of bytes. |
| Directory | Helps in manipulating a directory structure. |
| DirectoryInfo | Used for performing operations on directories. |
| DriveInfo | Provides information for the drives. |
| File | Helps in manipulating files. |
| FileInfo | Used for performing operations on files. |
| FileStream | Used to read from and write to any location in a file. |
| MemoryStream | Used for random access to streamed data stored in memory. |
| Path | Performs operations on path information. |
| StreamReader | Used for reading characters from a byte stream. |
| StreamWriter | Is used for writing characters to a stream. |
| StringReader | Is used for reading from a string buffer. |
| StringWriter | Is used for writing into a string buffer. |
The FileStream Class
The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream.
You need to create a FileStream object to create a new file or open an existing file. The syntax for creating aFileStream object is as follows:
Dim <object_name> As FileStream = New FileStream(<file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>)
For example, for creating a FileStream object F for reading a file named sample.txt:
Dim f1 As FileStream = New FileStream("test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite)
| Parameter | Description |
| FileMode |
The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are:
Append: It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist.
Create: It creates a new file.
CreateNew: It specifies to the operating system, that it should create a new file.
Open: It opens an existing file.
OpenOrCreate: It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file.
Truncate: It opens an existing file and truncates its size to zero bytes.
|
| FileAccess |
FileAccess enumerators have members: Read, ReadWrite and Write.
|
| FileShare |
FileShare enumerators have the following members:
Inheritable: It allows a file handle to pass inheritance to the child processes
None: It declines sharing of the current file
Read: It allows opening the file for reading
ReadWrite: It allows opening the file for reading and writing
Write: It allows opening the file for writing
|
Example:
The following program demonstrates use of the FileStream class:
Imports System.IO
Module fileProg
Sub Main()
Dim f1 As FileStream = New FileStream("test.dat", _
FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim i As Integer
For i = 0 To 20
f1.WriteByte(CByte(i))
Next i
f1.Position = 0
For i = 0 To 20
Console.Write("{0} ", f1.ReadByte())
Next i
f1.Close()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
Advanced File Operations in VB.Net
The preceding example provides simple file operations in VB.Net. However, to utilize the immense powers of System.IO classes, you need to know the commonly used properties and methods of these classes.
We will discuss these classes and the operations they perform, in the following sections. Please click the links provided to get to the individual sections:
| Topic and Description |
Reading from and Writing into Text files
It involves reading from and writing into text files. The StreamReader and StreamWriter class helps to accomplish it. |
Reading from and Writing into Binary files
It involves reading from and writing into binary files. The BinaryReader and BinaryWriter class helps to accomplish this. |
Manipulating the Windows file system
It gives a VB.Net programamer the ability to browse and locate Windows files and directories. |
The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.
The StreamReader Class
The StreamReader class also inherits from the abstract base class TextReader that represents a reader for reading series of characters. The following table describes some of the commonly used methods of the StreamReader class:
| S.N | Method Name & Purpose |
| 1 | Public Overrides Sub Close
It closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader. |
| 2 | Public Overrides Function Peek As Integer
Returns the next available character but does not consume it. |
| 3 | Public Overrides Function Read As Integer
Reads the next character from the input stream and advances the character position by one character. |
Example:
The following example demonstrates reading a text file named Jamaica.txt. The file reads:
Down the way where the nights are gay
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop
Imports System.IO
Module fileProg
Sub Main()
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As StreamReader = New StreamReader("e:/jamaica.txt")
Dim line As String
' Read and display lines from the file until the end of
' the file is reached.
line = sr.ReadLine()
While (line <> Nothing)
Console.WriteLine(line)
line = sr.ReadLine()
End While
End Using
Catch e As Exception
' Let the user know what went wrong.
Console.WriteLine("The file could not be read:")
Console.WriteLine(e.Message)
End Try
Console.ReadKey()
End Sub
End Module
Guess what it displays when you compile and run the program!
The StreamWriter Class
The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series of character.
The following table shows some of the most commonly used methods of this class:
| S.N | Method Name & Purpose |
| 1 | Public Overrides Sub Close
Closes the current StreamWriter object and the underlying stream. |
| 2 | Public Overrides Sub Flush
Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream. |
| 3 | Public Overridable Sub Write ( value As Boolean )
Writes the text representation of a Boolean value to the text string or stream. (Inherited from TextWriter.) |
| 4 | Public Overrides Sub Write ( value As Char )
Writes a character to the stream. |
| 5 | Public Overridable Sub Write ( value As Decimal )
Writes the text representation of a decimal value to the text string or stream. |
| 6 | Public Overridable Sub Write ( value As Double )
Writes the text representation of an 8-byte floating-point value to the text string or stream. |
| 7 | Public Overridable Sub Write ( value As Integer )
Writes the text representation of a 4-byte signed integer to the text string or stream. |
| 8 | Public Overrides Sub Write ( value As String )
Writes a string to the stream. |
| 9 | Public Overridable Sub WriteLine
Writes a line terminator to the text string or stream. |
The above list is not exhaustive. For complete list of methods please visit Microsoft's documentation
Example:
The following example demonstrates writing text data into a file using the StreamWriter class:
Imports System.IO
Module fileProg
Sub Main()
Dim names As String() = New String() {"Zara Ali", _
"Nuha Ali", "Amir Sohel", "M Amlan"}
Dim s As String
Using sw As StreamWriter = New StreamWriter("names.txt")
For Each s In names
sw.WriteLine(s)
Next s
End Using
' Read and show each line from the file.
Dim line As String
Using sr As StreamReader = New StreamReader("names.txt")
line = sr.ReadLine()
While (line <> Nothing)
Console.WriteLine(line)
line = sr.ReadLine()
End While
End Using
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
Zara Ali
Nuha Ali
Amir Sohel
M Amlan
The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file.
The BinaryReader Class
The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing aFileStream object to its constructor.
The following table shows some of the commonly used methods of the BinaryReader class.
| S.N | Method Name & Purpose |
| 1 | Public Overridable Sub Close
It closes the BinaryReader object and the underlying stream. |
| 2 | Public Overridable Function Read As Integer
Reads the characters from the underlying stream and advances the current position of the stream. |
| 3 | Public Overridable Function ReadBoolean As Boolean
Reads a Boolean value from the current stream and advances the current position of the stream by one byte. |
| 4 | Public Overridable Function ReadByte As Byte
Reads the next byte from the current stream and advances the current position of the stream by one byte. |
| 5 | Public Overridable Function ReadBytes ( count As Integer ) As Byte()
Reads the specified number of bytes from the current stream into a byte array and advances the current position by that number of bytes. |
| 6 | Public Overridable Function ReadChar As Char
Reads the next character from the current stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream. |
| 7 | Public Overridable Function ReadChars ( count As Integer ) As Char()
Reads the specified number of characters from the current stream, returns the data in a character array, and advances the current position in accordance with the Encoding used and the specific character being read from the stream. |
| 8 | Public Overridable Function ReadDouble As Double
Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes. |
| 9 | Public Overridable Function ReadInt32 As Integer
Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes. |
| 10 | Public Overridable Function ReadString As String
Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time. |
The BinaryWriter Class
The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor.
The following table shows some of the commonly used methods of the BinaryWriter class.
| S.N | Function Name & Description |
| 1 | Public Overridable Sub Close
It closes the BinaryWriter object and the underlying stream. |
| 2 | Public Overridable Sub Flush
Clears all buffers for the current writer and causes any buffered data to be written to the underlying device. |
| 3 | Public Overridable Function Seek ( offset As Integer, origin As SeekOrigin ) As Long
Sets the position within the current stream. |
| 4 | Public Overridable Sub Write ( value As Boolean )
Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing true. |
| 5 | Public Overridable Sub Write ( value As Byte )
Writes an unsigned byte to the current stream and advances the stream position by one byte. |
| 6 | Public Overridable Sub Write ( buffer As Byte() )
Writes a byte array to the underlying stream. |
| 7 | Public Overridable Sub Write ( ch As Char )
Writes a Unicode character to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream. |
| 8 | Public Overridable Sub Write ( chars As Char() )
Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream. |
| 9 | Public Overridable Sub Write ( value As Double )
Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes. |
| 10 | Public Overridable Sub Write ( value As Integer )
Writes a four-byte signed integer to the current stream and advances the stream position by four bytes. |
| 11 | Public Overridable Sub Write ( value As String )
Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter, and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream. |
For complete list of methods, please visit Microsoft's documentation.
Example
The following example demonstrates reading and writing binary data:
Imports System.IO
Module fileProg
Sub Main()
Dim bw As BinaryWriter
Dim br As BinaryReader
Dim i As Integer = 25
Dim d As Double = 3.14157
Dim b As Boolean = True
Dim s As String = "I am happy"
'create the file
Try
bw = New BinaryWriter(New FileStream("mydata", FileMode.Create))
Catch e As IOException
Console.WriteLine(e.Message + "\n Cannot create file.")
Return
End Try
'writing into the file
Try
bw.Write(i)
bw.Write(d)
bw.Write(b)
bw.Write(s)
Catch e As IOException
Console.WriteLine(e.Message + "\n Cannot write to file.")
Return
End Try
bw.Close()
'reading from the file
Try
br = New BinaryReader(New FileStream("mydata", FileMode.Open))
Catch e As IOException
Console.WriteLine(e.Message + "\n Cannot open file.")
Return
End Try
Try
i = br.ReadInt32()
Console.WriteLine("Integer data: {0}", i)
d = br.ReadDouble()
Console.WriteLine("Double data: {0}", d)
b = br.ReadBoolean()
Console.WriteLine("Boolean data: {0}", b)
s = br.ReadString()
Console.WriteLine("String data: {0}", s)
Catch e As IOException
Console.WriteLine(e.Message + "\n Cannot read from file.")
Return
End Try
br.Close()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
Integer data: 25
Double data: 3.14157
Boolean data: True
String data: I am happy
VB.Net allows you to work with the directories and files using various directory and file related classes like, theDirectoryInfo class and the FileInfo class.
The DirectoryInfo Class
The DirectoryInfo class is derived from the FileSystemInfo class. It has various methods for creating, moving, and browsing through directories and subdirectories. This class cannot be inherited.
Following are some commonly used properties of the DirectoryInfo class:
| S.N | Property Name & Description |
| 1 | Attributes
Gets the attributes for the current file or directory. |
| 2 | CreationTime
Gets the creation time of the current file or directory. |
| 3 | Exists
Gets a Boolean value indicating whether the directory exists. |
| 4 | Extension
Gets the string representing the file extension. |
| 5 | FullName
Gets the full path of the directory or file. |
| 6 | LastAccessTime
Gets the time the current file or directory was last accessed. |
| 7 | Name
Gets the name of this DirectoryInfo instance. |
Following are some commonly used methods of the DirectoryInfo class:
| S.N | Method Name & Purpose |
| 1 | Public Sub Create
Creates a directory. |
| 2 | Public Function CreateSubdirectory ( path As String ) As DirectoryInfo
Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class. |
| 3 | Public Overrides Sub Delete
Deletes this DirectoryInfo if it is empty. |
| 4 | Public Function GetDirectories As DirectoryInfo()
Returns the subdirectories of the current directory. |
| 5 | Public Function GetFiles As FileInfo()
Returns a file list from the current directory. |
For complete list of properties and methods please visit Microsoft's documentation.
The FileInfo Class
The FileInfo class is derived from the FileSystemInfo class. It has properties and instance methods for creating, copying, deleting, moving, and opening of files, and helps in the creation of FileStream objects. This class cannot be inherited.
Following are some commonly used properties of the FileInfo class:
| S.N | Property Name & Description |
| 1 | Attributes
Gets the attributes for the current file. |
| 2 | CreationTime
Gets the creation time of the current file. |
| 3 | Directory
Gets an instance of the directory which the file belongs to. |
| 4 | Exists
Gets a Boolean value indicating whether the file exists. |
| 5 | Extension
Gets the string representing the file extension. |
| 6 | FullName
Gets the full path of the file. |
| 7 | LastAccessTime
Gets the time the current file was last accessed. |
| 8 | LastWriteTime
Gets the time of the last written activity of the file. |
| 9 | Length
Gets the size, in bytes, of the current file. |
| 10 | Name
Gets the name of the file. |
Following are some commonly used methods of the FileInfo class:
| S.N | Method Name & Purpose |
| 1 | Public Function AppendText As StreamWriter
Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo. |
| 2 | Public Function Create As FileStream
Creates a file. |
| 3 | Public Overrides Sub Delete
Deletes a file permanently. |
| 4 | Public Sub MoveTo ( destFileName As String )
Moves a specified file to a new location, providing the option to specify a new file name. |
| 5 | Public Function Open ( mode As FileMode ) As FileStream
Opens a file in the specified mode. |
| 6 | Public Function Open ( mode As FileMode, access As FileAccess ) As FileStream
Opens a file in the specified mode with read, write, or read/write access. |
| 7 | Public Function Open ( mode As FileMode, access As FileAccess, share As FileShare ) As FileStream
Opens a file in the specified mode with read, write, or read/write access and the specified sharing option. |
| 8 | Public Function OpenRead As FileStream
Creates a read-only FileStream |
| 9 | Public Function OpenWrite As FileStream
Creates a write-only FileStream. |
For complete list of properties and methods, please visit Microsoft's documentation
Example
The following example demonstrates the use of the above mentioned classes:
Imports System.IO
Module fileProg
Sub Main()
'creating a DirectoryInfo object
Dim mydir As DirectoryInfo = New DirectoryInfo("c:\Windows")
' getting the files in the directory, their names and size
Dim f As FileInfo() = mydir.GetFiles()
Dim file As FileInfo
For Each file In f
Console.WriteLine("File Name: {0} Size: {1} ", file.Name, file.Length)
Next file
Console.ReadKey()
End Sub
End Module
An object is a type of user interface element you create on a Visual Basic form by using a toolbox control. In fact, in Visual Basic, the form itself is also an object. Every Visual Basic control consists of three important elements:
Properties which describe the object,
Methods cause an object to do something and
Events are what happens when an object does something.
Control Properties
All the Visual Basic Objects can be moved, resized or customized by setting their properties. A property is a value or characteristic held by a Visual Basic object, such as Caption or Fore Color.
Properties can be set at design time by using the Properties window or at run time by using statements in the program code.
Object. Property = Value
Where
Object is the name of the object you're customizing.
Property is the characteristic you want to change.
Value is the new property setting.
For example,
Form1.Caption = "Hello"
You can set any of the form properties using Properties Windows. Most of the properties can be set or read during application execution. You can refer to Microsoft documentation for a complete list of properties associated with different controls and restrictions applied to them.
Control Methods
A method is a procedure created as a member of a class and they cause an object to do something. Methods are used to access or manipulate the characteristics of an object or a variable. There are mainly two categories of methods you will use in your classes:
If you are using a control such as one of those provided by the Toolbox, you can call any of its public methods. The requirements of such a method depend on the class being used
If none of the existing methods can perform your desired task, you can add a method to a class.
For example, the MessageBox control has a method named Show, which is called in the code snippet below:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
MessageBox.Show("Hello, World")
End Sub
End Class
Control Events
An event is a signal that informs an application that something important has occurred. For example, when a user clicks a control on a form, the form can raise a Click event and call a procedure that handles the event. There are various types of events associated with a Form like click, double click, close, load , resize etc.
Following is the default structure of a form Load event handler subroutine. You can see this code by double clicking the code which will give you a complete list of the all events associated with Form control:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'event handler code goes here
End Sub
Here Handles MyBase.Load indicates that Form1_Load() subroutine handles Load event. Similar way you can check stub code for click, double click If you want to initialize some variables like properties etc. then you will keep such code inside Form1_Load() subroutine. Here important point to note is the name of the event handler which is by default Form1_Load, but you can change this name based on your naming convention you use in your application programming.
Basic Controls
VB.Net provides a huge variety of controls that help you to create rich user interface. Functionalities of all these controls are defined in the respective control classes. The control classes are defined in theSystem.Windows.Forms namespace.
The following table lists some of the commonly used controls:
| S.N. | Widget & Description |
| 1 | Forms
The container for all the controls that make up the user interface |
| 2 | TextBox
It represents a Windows text box control. |
| 3 | Label
It represents a standard Windows label. |
| 4 | Button
It represents a Windows button control. |
| 5 | ListBox
It represents a Windows control to display a list of items. |
| 6 | ComboBox
It represents a Windows combo box control. |
| 7 | RadioButton
It enables the user to select a single option from a group of choices when paired with other RadioButton controls. |
| 8 | CheckBox
Represents a Windows CheckBox. |
| 9 | PictureBox
It represents a Windows picture box control for displaying an image. |
| 10 | ProgressBar
It represents a Windows progress bar control. |
| 11 | ScrollBar
It Implements the basic functionality of a scroll bar control. |
| 12 | DateTimePicker
It represents a Windows control that allows the user to select a date and a time and to display the date and time with a specified format. |
| 13 | TreeView
It displays a hierarchical collection of labeled items, each represented by a TreeNode. |
| 14 | ListView
It represents a Windows list view control, which displays a collection of items that can be displayed using one of four different views. |
Let's start with creating a Window Forms Application by following the following steps in Microsoft Visual Studio:File -> New Project -> Windows Forms Applications
Finally select OK, Microsoft Visual Studio your project and displays following window with a default Form with a name Form1.

Visual Basic Form is the container for all the controls that make up the user interface. Every window you see in a running visual basic application is a form, thus the terms form and window describe the same entity. Visual Studio creates a default form for you when you create a Windows Forms Application.
Every form will have title bar on which the form's caption is displayed and there will be buttons to close, maximize and minimize the form shown below:

If you click the icon on the top left corner, it opens the control menu, which contains the various commands to control the form like to move control from one place to another place, to maximize or minimize the form or to close the form.
Form Properties
Following table lists down various important properties related to a form. These properties can be set or read during application execution. You can refer to Microsoft documentation for a complete list of properties associated with a Form control:
| S.N | Properties | Description |
| 1 | AcceptButton | The button that's automatically activated when you press Enter, no matter which control has the focus at the time. Usually the OK button on a form is set as AcceptButton for a form. |
| 2 | CancelButton | The button that's automatically activated when you hit the Esc key.
Usually the Cancel button on a form is set as CancelButton for a form. |
| 3 | AutoScale | This Boolean property determines whether the controls you place on the form are automatically scaled to the height of the current font. The default value of this property is True. This is a property of the form, but it affects the controls on the form. |
| 4 | AutoScroll | This Boolean property indicates whether scroll bars will be automatically attached to the form if it is resized to a point that not all its controls are visible. |
| 5 | AutoScrollMinSize | This property lets you specify the minimum size of the form, before the scroll bars are attached. |
| 6 | AutoScrollPosition | The AutoScrollPosition is the number of pixels by which the two scroll bars were displaced from their initial locations. |
| 7 | BackColor | Sets the form background color. |
| 8 | BorderStyle | The BorderStyle property determines the style of the form's border and the appearance of the form:
- None: Borderless window that can't be resized.
- Sizable: This is default value and will be used for resizable window that's used for displaying regular forms.
- Fixed3D: Window with a visible border, "raised" relative to the main area. In this case windows can't be resized.
- FixedDialog: A fixed window, used to create dialog boxes.
- FixedSingle: A fixed window with a single line border.
- FixedToolWindow: A fixed window with a Close button only. It looks like the toolbar displayed by the drawing and imaging applications.
- SizableToolWindow: Same as the FixedToolWindow but resizable. In addition, its caption font is smaller than the usual.
|
| 9 | ControlBox | By default this property is True and you can set it to False to hide the icon and disable the Control menu. |
| 10 | Enabled | If True, allows the form to respond to mouse and keyboard events; if False, disables form. |
| 11 | Font | This property specify font type, style, size |
| 12 | HelpButton | Determines whether a Help button should be displayed in the caption box of the form. |
| 13 | Height | This is the height of the Form in pixels. |
| 14 | MinimizeBox | By default this property is True and you can set it to False to hide the Minimize button on the title bar. |
| 15 | MaximizeBox | By default this property is True and you can set it to False to hide the Maximize button on the title bar. |
| 16 | MinimumSize | This specifies the minimum height and width of the window you can minimize. |
| 17 | MaximumSize | This specifies the maximum height and width of the window you maximize. |
| 18 | Name | This is the actual name of the form. |
| 19 | StartPosition | This property determines the initial position of the form when it's first displayed. It will have any of the following values:
- CenterParent The form is centered in the area of its parent form.
- CenterScreen The form is centered on the monitor.
- Manual The location and size of the form will determine its starting position..
- WindowsDefaultBounds The form is positioned at the default location and size determined by Windows.
- WindowsDefaultLocation The form is positioned at the Windows default location and has the dimensions you've set at design time.
|
| 20 | Text | The text which will appear at the title bar of the form. |
| 21 | Top, Left | These two properties set or return the coordinates of the form's top-left corner in pixels. |
| 22 | TopMost | This property is a True/False value that lets you specify whether the form will remain on top of all other forms in your application. Its default property is False. |
| 23 | Width | This is the width of the form in pixel. |
Form Methods
The following are some of the commonly used methods of the Form class.You can refer to Microsoft documentation for a complete list of methods associated with forms control:
| S.N. | Method Name & Description |
| 1 | Activate
Activates the form and gives it focus. |
| 2 | ActivateMdiChild
Activates the MDI child of a form. |
| 3 | AddOwnedForm
Adds an owned form to this form. |
| 4 | BringToFront
Brings the control to the front of the z-order. |
| 5 | CenterToParent
Centers the position of the form within the bounds of the parent form. |
| 6 | CenterToScreen
Centers the form on the current screen. |
| 7 | Close
Closes the form. |
| 8 | Contains
Retrieves a value indicating whether the specified control is a child of the control. |
| 9 | Focus
Sets input focus to the control. |
| 10 | Hide
Conceals the control from the user. |
| 11 | Refresh
Forces the control to invalidate its client area and immediately redraw itself and any child controls. |
| 12 | Scale(SizeF)
Scales the control and all child controls by the specified scaling factor. |
| 13 | ScaleControl
Scales the location, size, padding, and margin of a control. |
| 14 | ScaleCore
Performs scaling of the form. |
| 15 | Select
Activates the control. |
| 16 | SendToBack
Sends the control to the back of the z-order. |
| 17 | SetAutoScrollMargin
Sets the size of the auto-scroll margins. |
| 18 | SetDesktopBounds
Sets the bounds of the form in desktop coordinates. |
| 19 | SetDesktopLocation
Sets the location of the form in desktop coordinates. |
| 20 | SetDisplayRectLocation
Positions the display window to the specified value. |
| 21 | Show
Displays the control to the user. |
| 22 | ShowDialog
Shows the form as a modal dialog box. |
Form Events
Following table lists down various important events related to a form. You can refer to Microsoft documentation for a complete list of events associated with forms control:
| S.N | Event | Description |
| 1 | Activated | Occurs when the form is activated in code or by the user. |
| 2 | Click | Occurs when the form is clicked. |
| 3 | Closed | Occurs before the form is closed. |
| 4 | Closing | Occurs when the form is closing. |
| 5 | DoubleClick | Occurs when the form control is double-clicked. |
| 6 | DragDrop | Occurs when a drag-and-drop operation is completed. |
| 7 | Enter | Occurs when the form is entered. |
| 8 | GotFocus | Occurs when the form control receives focus. |
| 9 | HelpButtonClicked | Occurs when the Help button is clicked. |
| 10 | KeyDown | Occurs when a key is pressed while the form has focus. |
| 11 | KeyPress | Occurs when a key is pressed while the form has focus. |
| 12 | KeyUp | Occurs when a key is released while the form has focus. |
| 13 | Load | Occurs before a form is displayed for the first time. |
| 14 | LostFocus | Occurs when the form loses focus. |
| 15 | MouseDown | Occurs when the mouse pointer is over the form and a mouse button is pressed. |
| 16 | MouseEnter | Occurs when the mouse pointer enters the form. |
| 17 | MouseHover | Occurs when the mouse pointer rests on the form. |
| 18 | MouseLeave | Occurs when the mouse pointer leaves the form. |
| 19 | MouseMove | Occurs when the mouse pointer is moved over the form. |
| 20 | MouseUp | Occurs when the mouse pointer is over the form and a mouse button is released. |
| 21 | MouseWheel | Occurs when the mouse wheel moves while the control has focus. |
| 22 | Move | Occurs when the form is moved. |
| 23 | Resize | Occurs when the control is resized. |
| 24 | Scroll | Occurs when the user or code scrolls through the client area. |
| 25 | Shown | Occurs whenever the form is first displayed. |
| 26 | VisibleChanged | Occurs when the Visible property value changes. |
Example:
Following is an example which shows how we create two buttons at the time of form load event and different properties are being set at the same time.
Because Form1 is being referenced with-in its own event handler so it will be written as Me instead of using its name, but if we access the same form inside any other control's event handler then it will access using its nameForm1.
Let's double click on the Form and put the follow code in the opened window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Create two buttons to use as the accept and cancel buttons.
Dim button1 As New Button()
Dim button2 As New Button()
' Set the text of button1 to "OK".
button1.Text = "OK"
' Set the position of the button on the form.
button1.Location = New Point(10, 10)
' Set the text of button2 to "Cancel".
button2.Text = "Cancel"
' Set the position of the button based on the location of button1.
button2.Location = _
New Point(button1.Left, button1.Height + button1.Top + 10)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
' Display a help button on the form.
Me.HelpButton = True
' Define the border style of the form to a dialog box.
Me.FormBorderStyle = FormBorderStyle.FixedDialog
' Set the MaximizeBox to false to remove the maximize box.
Me.MaximizeBox = False
' Set the MinimizeBox to false to remove the minimize box.
Me.MinimizeBox = False
' Set the accept button of the form to button1.
Me.AcceptButton = button1
' Set the cancel button of the form to button2.
Me.CancelButton = button2
' Set the start position of the form to the center of the screen.
Me.StartPosition = FormStartPosition.CenterScreen
' Set window width and height
Me.Height = 300
Me.Width = 560
' Add button1 to the form.
Me.Controls.Add(button1)
' Add button2 to the form.
Me.Controls.Add(button2)
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:

Text box controls allow entering text on a form at runtime. By default, it takes a single line of text, however, you can make it accept multiple texts and even add scroll bars to it.
Let's create a text box by dragging a Text Box control from the Toolbox and dropping it on the form.

The Properties of the TextBox Control
The following are some of the commonly used properties of the TextBox control:
| S.N | Property | Description |
| 1 | AcceptsReturn | Gets or sets a value indicating whether pressing ENTER in a multiline TextBox control creates a new line of text in the control or activates the default button for the form. |
| 2 | AutoCompleteCustomSource | Gets or sets a custom System.Collections.Specialized.StringCollection to use when the AutoCompleteSourceproperty is set to CustomSource. |
| 3 | AutoCompleteMode | Gets or sets an option that controls how automatic completion works for the TextBox. |
| 4 | AutoCompleteSource | Gets or sets a value specifying the source of complete strings used for automatic completion. |
| 5 | CharacterCasing | Gets or sets whether the TextBox control modifies the case of characters as they are typed. |
| 6 | Font | Gets or sets the font of the text displayed by the control. |
| 7 | FontHeight | Gets or sets the height of the font of the control. |
| 8 | ForeColor | Gets or sets the foreground color of the control. |
| 9 | Lines | Gets or sets the lines of text in a text box control. |
| 10 | Multiline | Gets or sets a value indicating whether this is a multiline TextBox control. |
| 11 | PasswordChar | Gets or sets the character used to mask characters of a password in a single-line TextBox control. |
| 12 | ReadOnly | Gets or sets a value indicating whether text in the text box is read-only. |
| 13 | ScrollBars | Gets or sets which scroll bars should appear in a multiline TextBox control. This property has values:
- None
- Horizontal
- Vertical
- Both
|
| 14 | TabIndex | Gets or sets the tab order of the control within its container. |
| 15 | Text | Gets or sets the current text in the TextBox. |
| 16 | TextAlign | Gets or sets how text is aligned in a TextBox control. This property has values:
|
| 17 | TextLength | Gets the length of text in the control. |
| 18 | WordWrap | Indicates whether a multiline text box control automatically wraps words to the beginning of the next line when necessary. |
The Methods of the TextBox Control
The following are some of the commonly used methods of the TextBox control:
| S.N | Method Name & Description |
| 1 | AppendText
Appends text to the current text of a text box. |
| 2 | Clear
Clears all text from the text box control. |
| 3 | Copy
Copies the current selection in the text box to the Clipboard. |
| 4 | Cut
Moves the current selection in the text box to the Clipboard. |
| 5 | Paste
Replaces the current selection in the text box with the contents of the Clipboard. |
| 6 | Paste(String)
Sets the selected text to the specified text without clearing the undo buffer. |
| 7 | ResetText
Resets the Text property to its default value. |
| 8 | ToString
Returns a string that represents the TextBoxBase control. |
| 9 | Undo
Undoes the last edit operation in the text box. |
Events of the TextBox Control
The following are some of the commonly used events of the Text control:
| S.N | Event | Description |
| 1 | Click | Occurs when the control is clicked. |
| 2 | DoubleClick | Occurs when the control is double-clicked. |
| 3 | TextAlignChanged | Occurs when the TextAlign property value changes. |
Example
In this example, we create three text boxes and use the Click event of a button to display the entered text using a message box. Take the following steps:
Drag and drop three Label controls and three TextBox controls on the form.
Change the texts on the labels to: Name, Organization and Comments respectively.
Change the names of the text boxes to txtName, txtOrg and txtComment respectively.
Drag and drop a button control on the form. Set its name to btnMessage and its text property to 'Send Message'.
Click the button to add the Click event in the code window and add the following code.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
Private Sub btnMessage_Click(sender As Object, e As EventArgs) _
Handles btnMessage.Click
MessageBox.Show("Thank you " + txtName.Text + " from " + txtOrg.Text)
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:

Clicking the Send Message button would show the following message box:

The Label control represents a standard Windows label. It is generally used to display some informative text on the GUI, which is not changed during runtime.
Let's create a label by dragging a Label control from the Toolbox and dropping it on the form.

Properties of the Label Control
The following are some of the commonly used properties of the Label control:
| S.N | Property | Description |
| 1 | Autosize | Gets or sets a value specifying if the control should be automatically resized to display all its contents. |
| 2 | BorderStyle | Gets or sets the border style for the control. |
| 3 | FlatStyle | Gets or sets the flat style appearance of the Label control |
| 4 | Font | Gets or sets the font of the text displayed by the control. |
| 5 | FontHeight | Gets or sets the height of the font of the control. |
| 6 | ForeColor | Gets or sets the foreground color of the control. |
| 7 | PreferredHeight | Gets the preferred height of the control. |
| 8 | PreferredWidth | Gets the preferred width of the control. |
| 9 | TabStop | Gets or sets a value indicating whether the user can tab to the Label. This property is not used by this class. |
| 10 | Text | Gets or sets the text associated with this control. |
| 11 | TextAlign | Gets or sets the alignment of text in the label. |
Methods of the Label Control
The following are some of the commonly used methods of the Label control:
| S.N | Method Name & Description |
| 1 | GetPreferredSize
Retrieves the size of a rectangular area into which a control can be fitted. |
| 2 | Refresh
Forces the control to invalidate its client area and immediately redraw itself and any child controls. |
| 3 | Select
Activates the control. |
| 4 | Show
Displays the control to the user. |
| 5 | ToString
Returns a String that contains the name of the control. |
Events of the Label Control
The following are some of the commonly used events of the Label control:
| S.N | Event | Description |
| 1 | AutoSizeChanged | Occurs when the value of the AutoSize property changes. |
| 2 | Click | Occurs when the control is clicked. |
| 3 | DoubleClick | Occurs when the control is double-clicked. |
| 4 | GotFocus | Occurs when the control receives focus. |
| 5 | Leave | Occurs when the input focus leaves the control. |
| 6 | LostFocus | Occurs when the control loses focus. |
| 7 | TabIndexChanged | Occurs when the TabIndex property value changes. |
| 8 | TabStopChanged | Occurs when the TabStop property changes. |
| 9 | TextChanged | Occurs when the Text property value changes. |
Consult Microsoft documentation for detailed list of properties, methods and events of the Label control.
Example
Following is an example which shows how we create two labels. Let us create the first label from the designer view tab and set its properties from the properties window. We will use the Click and the DoubleClick events of the label to move the first label and change its text and create the second label and add it to the form respectively.
Take the following steps:
Drag and drop a Label control on the form.
Set the Text property to provide the caption "This is a Label Control".
Set the Font property from the properties window.
Click the label to add the Click event in the code window and add the following codes.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
' Create two buttons to use as the accept and cancel buttons.
' Set window width and height
Me.Height = 300
Me.Width = 560
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
' Display a help button on the form.
Me.HelpButton = True
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) _
Handles Label1.Click
Label1.Location = New Point(50, 50)
Label1.Text = "You have just moved the label"
End Sub
Private Sub Label1_DoubleClick(sender As Object, e As EventArgs)
Handles Label1.DoubleClick
Dim Label2 As New Label
Label2.Text = "New Label"
Label2.Location = New Point(Label1.Left, Label1.Height + _
Label1.Top + 25)
Me.Controls.Add(Label2)
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:

Clicking and double clicking the label would produce the following effect:

The Button control represents a standard Windows button. It is generally used to generate a Click event by providing a handler for the Click event.
Let's create a label by dragging a Button control from the Toolbox ad dropping it on the form.

Properties of the Button Control
The following are some of the commonly used properties of the Button control:
| S.N | Property | Description |
| 1 | AutoSizeMode | Gets or sets the mode by which the Button automatically resizes itself. |
| 2 | BackColor | Gets or sets the background color of the control. |
| 3 | BackgroundImage | Gets or sets the background image displayed in the control. |
| 4 | DialogResult | Gets or sets a value that is returned to the parent form when the button is clicked. This is used while creating dialog boxes. |
| 5 | ForeColor | Gets or sets the foreground color of the control. |
| 6 | Image | Gets or sets the image that is displayed on a button control. |
| 7 | Location | Gets or sets the coordinates of the upper-left corner of the control relative to the upper-left corner of its container. |
| 8 | TabIndex | Gets or sets the tab order of the control within its container. |
| 9 | Text | Gets or sets the text associated with this control. |
Methods of the Button Control
The following are some of the commonly used methods of the Button control:
| S.N | Method Name & Description |
| 1 | GetPreferredSize
Retrieves the size of a rectangular area into which a control can be fitted. |
| 2 | NotifyDefault
Notifies the Button whether it is the default button so that it can adjust its appearance accordingly. |
| 3 | Select
Activates the control. |
| 4 | ToString
Returns a String containing the name of the Component, if any. This method should not be overridden. |
Events of the Button Control
The following are some of the commonly used events of the Button control:
| S.N | Event | Description |
| 1 | Click | Occurs when the control is clicked. |
| 2 | DoubleClick | Occurs when the user double-clicks the Button control. |
| 3 | GotFocus | Occurs when the control receives focus. |
| 4 | TabIndexChanged | Occurs when the TabIndex property value changes. |
| 5 | TextChanged | Occurs when the Text property value changes. |
| 6 | Validated | Occurs when the control is finished validating. |
Consult Microsoft documentation for detailed list of properties, methods and events of the Button control.
Example
In the following example, we create three buttons. In this example, let us:
Set captions for the buttons
Set some image for the button
Handle the click events of each buttons
Take following steps:
Drag and drop a Label control on the form.
Set the Text property to provide the caption "Tutorials Point".
Drag and drop three buttons on the form.
Using the properties window, change the Name properties of the buttons to btnMoto, btnLogo and btnExit respectively.
Using the properties window, change the Text properties of the buttons to Show Moto, Show Logo and Exit respectively.
Drag and Drop another button, using the properties window, set its Image property and name it btnImage.
At this stage, the form looks like:

Click the form and add following code in the code editor:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
btnImage.Visible = False
End Sub
Private Sub btnMoto_Click(sender As Object, e As EventArgs) Handles btnMoto.Click
btnImage.Visible = False
Label1.Text = "Simple Easy Learning"
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Application.Exit()
End Sub
Private Sub btnLogo_Click(sender As Object, e As EventArgs) Handles btnLogo.Click
Label1.Visible = False
btnImage.Visible = True
End Sub
End Class
Clicking the first button, displays:

Clicking the second button displays:

Clicking the third button, exits the application.
The ListBox represents a Windows control to display a list of items to a user. A user can select an item from the list. It allows the programmer to add items at design time by using the properties window, or at the runtime.
Let's create a list box by dragging a ListBox control from the Toolbox and dropping it on the form.

You can populate the list box items either from the properties window or at runtime. To add items to a ListBox, select the ListBox control and get to the properties window, for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line.
Properties of the ListBox Control
The following are some of the commonly used properties of the ListBox control:
| S.N | Property | Description |
| 1 | AllowSelection | Gets a value indicating whether the ListBox currently enables selection of list items. |
| 2 | BorderStyle | Gets or sets the type of border drawn around the list box. |
| 3 | ColumnWidth | Gets of sets the width of columns in a multicolumn list box. |
| 4 | HorizontalExtent | Gets or sets the horizontal scrolling area of a list box. |
| 5 | HorizontalScrollBar | Gets or sets the value indicating whether a horizontal scrollbar is displayed in the list box. |
| 6 | ItemHeight | Gets or sets the height of an item in the list box. |
| 7 | Items | Gets the items of the list box. |
| 8 | MultiColumn | Gets or sets a value indicating whether the list box supports multiple columns. |
| 9 | ScrollAlwaysVisible | Gets or sets a value indicating whether the vertical scroll bar is shown at all times. |
| 10 | SelectedIndex | Gets or sets the zero-based index of the currently selected item in a list box. |
| 11 | SelectedIndices | Gets a collection that contains the zero-based indexes of all currently selected items in the list box. |
| 12 | SelectedItem | Gets or sets the currently selected item in the list box. |
| 13 | SelectedItems | Gets a collection containing the currently selected items in the list box. |
| 14 | SelectedValue | Gets or sets the value of the member property specified by the ValueMember property. |
| 15 | SelectionMode | Gets or sets the method in which items are selected in the list box. This property has values:
- None
- One
- MultiSimple
- MultiExtended
|
| 16 | Sorted | Gets or sets a value indicating whether the items in the list box are sorted alphabetically. |
| 17 | Text | Gets or searches for the text of the currently selected item in the list box. |
| 18 | TopIndex | Gets or sets the index of the first visible item of a list box. |
Methods of the ListBox Control
The following are some of the commonly used methods of the ListBox control:
| S.N | Method Name & Description |
| 1 | BeginUpdate
Prevents the control from drawing until the EndUpdate method is called, while items are added to the ListBox one at a time. |
| 2 | ClearSelected
Unselects all items in the ListBox. |
| 3 | EndUpdate
Resumes drawing of a list box after it was turned off by the BeginUpdate method. |
| 4 | FindString
Finds the first item in the ListBox that starts with the string specified as an argument. |
| 5 | FindStringExact
Finds the first item in the ListBox that exactly matches the specified string. |
| 6 | GetSelected
Returns a value indicating whether the specified item is selected. |
| 7 | SetSelected
Selects or clears the selection for the specified item in a ListBox. |
| 8 | OnSelectedIndexChanged
Raises the SelectedIndexChanged event. |
| 8 | OnSelectedValueChanged
Raises the SelectedValueChanged event. |
Events of the ListBox Control
The following are some of the commonly used events of the ListBox control:
| S.N | Event | Description |
| 1 | Click | Occurs when a list box is selected. |
| 2 | SelectedIndexChanged | Occurs when the SelectedIndex property of a list box is changed. |
Consult Microsoft documentation for detailed list of properties, methods and events of the ListBox control.
Example 1
In the following example, let us add a list box at design time and add items on it at runtime.
Take the following steps:
Drag and drop two labels, a button and a ListBox control on the form.
Set the Text property of the first label to provide the caption "Choose your favourite destination for higher studies".
Set the Text property of the second label to provide the caption "Destination". The text on this label will change at runtime, when the user selects an item on the list.
Click the listbox and the button controls to add the following codes in the code editor.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
ListBox1.Items.Add("Canada")
ListBox1.Items.Add("USA")
ListBox1.Items.Add("UK")
ListBox1.Items.Add("Japan")
ListBox1.Items.Add("Russia")
ListBox1.Items.Add("China")
ListBox1.Items.Add("India")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox("You have selected " + ListBox1.SelectedItem.ToString())
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
Handles ListBox1.SelectedIndexChanged
Label2.Text = ListBox1.SelectedItem.ToString()
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:

When the user chooses a destination, the text in the second label changes:

Clicking the Select button, displays a message box with the user's choice:

Example 2
In this example, we will fill up a list box with items, retrieve the total number of items in the list box, sort the list box, remove some items and clear the entire list box.
Design the Form:

Add the following code in the code editor window:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
' creating multi-column and multiselect list box
ListBox1.MultiColumn = True
ListBox1.SelectionMode = SelectionMode.MultiExtended
End Sub
'populates the list
Private Sub Button1_Click_1(sender As Object, e As EventArgs) _
Handles Button1.Click
ListBox1.Items.Add("Safety")
ListBox1.Items.Add("Security")
ListBox1.Items.Add("Governance")
ListBox1.Items.Add("Good Music")
ListBox1.Items.Add("Good Movies")
ListBox1.Items.Add("Good Books")
ListBox1.Items.Add("Education")
ListBox1.Items.Add("Roads")
ListBox1.Items.Add("Health")
ListBox1.Items.Add("Food for all")
ListBox1.Items.Add("Shelter for all")
ListBox1.Items.Add("Industrialisation")
ListBox1.Items.Add("Peace")
ListBox1.Items.Add("Liberty")
ListBox1.Items.Add("Freedom of Speech")
End Sub
'sorting the list
Private Sub Button2_Click(sender As Object, e As EventArgs) _
Handles Button2.Click
ListBox1.Sorted = True
End Sub
'clears the list
Private Sub Button3_Click(sender As Object, e As EventArgs) _
Handles Button3.Click
ListBox1.Items.Clear()
End Sub
'removing the selected item
Private Sub Button4_Click(sender As Object, e As EventArgs) _
Handles Button4.Click
ListBox1.Items.Remove(ListBox1.SelectedItem.ToString)
End Sub
'counting the numer of items
Private Sub Button5_Click(sender As Object, e As EventArgs) _
Handles Button5.Click
Label1.Text = ListBox1.Items.Count
End Sub
'displaying the selected item on the third label
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _
Handles ListBox1.SelectedIndexChanged
Label3.Text = ListBox1.SelectedItem.ToString()
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:

Fill the list and check workings of other buttons:

The ComboBox control is used to display a drop-down list of various items. It is a combination of a text box in which the user enters an item and a drop-down list from which the user selects an item.
Let's create a combo box by dragging a ComboBox control from the Toolbox and dropping it on the form.

You can populate the list box items either from the properties window or at runtime. To add items to a ListBox, select the ListBox control and get to the properties window, for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line.
Properties of the ComboBox Control
The following are some of the commonly used properties of the ComboBox control:
| S.N | Property | Description |
| 1 | AllowSelection | Gets a value indicating whether the list enables selection of list items. |
| 2 | AutoCompleteCustomSource | Gets or sets a custom System.Collections.Specialized.StringCollection to use when the AutoCompleteSourceproperty is set to CustomSource. |
| 3 | AutoCompleteMode | Gets or sets an option that controls how automatic completion works for the ComboBox. |
| 4 | AutoCompleteSource | Gets or sets a value specifying the source of complete strings used for automatic completion. |
| 5 | DataBindings | Gets the data bindings for the control. |
| 6 | DataManager | Gets the CurrencyManager associated with this control. |
| 7 | DataSource | Gets or sets the data source for this ComboBox. |
| 8 | DropDownHeight | Gets or sets the height in pixels of the drop-down portion of the ComboBox. |
| 9 | DropDownStyle | Gets or sets a value specifying the style of the combo box. |
| 10 | DropDownWidth | Gets or sets the width of the of the drop-down portion of a combo box. |
| 11 | DroppedDown | Gets or sets a value indicating whether the combo box is displaying its drop-down portion. |
| 12 | FlatStyle | Gets or sets the appearance of the ComboBox. |
| 13 | ItemHeight | Gets or sets the height of an item in the combo box. |
| 14 | Items | Gets an object representing the collection of the items contained in this ComboBox. |
| 15 | MaxDropDownItems | Gets or sets the maximum number of items to be displayed in the drop-down part of the combo box. |
| 16 | MaxLength | Gets or sets the maximum number of characters a user can enter in the editable area of the combo box. |
| 17 | SelectedIndex | Gets or sets the index specifying the currently selected item. |
| 18 | SelectedItem | Gets or sets currently selected item in the ComboBox. |
| 19 | SelectedText | Gets or sets the text that is selected in the editable portion of a ComboBox. |
| 20 | SelectedValue | Gets or sets the value of the member property specified by the ValueMember property. |
| 21 | SelectionLength | Gets or sets the number of characters selected in the editable portion of the combo box. |
| 22 | SelectionStart | Gets or sets the starting index of text selected in the combo box. |
| 23 | Sorted | Gets or sets a value indicating whether the items in the combo box are sorted. |
| 24 | Text | Gets or sets the text associated with this control. |
Methods of the ComboBox Control
The following are some of the commonly used methods of the ComboBox control:
| S.N | Method Name & Description |
| 1 | BeginUpdate
Prevents the control from drawing until the EndUpdate method is called, while items are added to the combo box one at a time. |
| 2 | EndUpdate
Resumes drawing of a combo box, after it was turned off by the BeginUpdate method. |
| 3 | FindString
Finds the first item in the combo box that starts with the string specified as an argument. |
| 4 | FindStringExact
Finds the first item in the combo box that exactly matches the specified string. |
| 5 | SelectAll
Selects all the text in the editable area of the combo box. |
Events of the ComboBox Control
The following are some of the commonly used events of the ComboBox control:
| S.N | Event | Description |
| 1 | DropDown | Occurs when the drop-down portion of a combo box is displayed. |
| 2 | DropDownClosed | Occurs when the drop-down portion of a combo box is no longer visible. |
| 3 | DropDownStyleChanged | Occurs when the DropDownStyle property of the ComboBox has changed. |
| 4 | SelectedIndexChanged | Occurs when the SelectedIndex property of a ComboBox control has changed. |
| 5 | SelectionChangeCommitted | Occurs when the selected item has changed and the change appears in the combo box. |
Example
In this example, let us fill a combo box with various items, get the selected items in the combo box and show them in a list box and sort the items.
Drag and drop a combo box to store the items, a list box to display the selected items, four button controls to add to the list box with selected items, to fill the combo box, to sort the items and to clear the combo box list respectively.
Add a label control that would display the selected item.

Add the following code in the code editor window:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
'sends the selected items to the list box
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex > -1 Then
Dim sindex As Integer
sindex = ComboBox1.SelectedIndex
Dim sitem As Object
sitem = ComboBox1.SelectedItem
ListBox1.Items.Add(sitem)
End If
End Sub
'populates the list
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
ComboBox1.Items.Clear()
ComboBox1.Items.Add("Safety")
ComboBox1.Items.Add("Security")
ComboBox1.Items.Add("Governance")
ComboBox1.Items.Add("Good Music")
ComboBox1.Items.Add("Good Movies")
ComboBox1.Items.Add("Good Books")
ComboBox1.Items.Add("Education")
ComboBox1.Items.Add("Roads")
ComboBox1.Items.Add("Health")
ComboBox1.Items.Add("Food for all")
ComboBox1.Items.Add("Shelter for all")
ComboBox1.Items.Add("Industrialisation")
ComboBox1.Items.Add("Peace")
ComboBox1.Items.Add("Liberty")
ComboBox1.Items.Add("Freedom of Speech")
ComboBox1.Text = "Select from..."
End Sub
'sorting the list
Private Sub Button3_Click(sender As Object, e As EventArgs)
ComboBox1.Sorted = True
End Sub
'clears the list
Private Sub Button4_Click(sender As Object, e As EventArgs)
ComboBox1.Items.Clear()
End Sub
'displaying the selected item on the label
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _
Handles ListBox1.SelectedIndexChanged
Label1.Text = ComboBox1.SelectedItem.ToString()
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:

Click on various buttons to check the actions performed by each:

The ComboBox control is used to display a drop-down list of various items. It is a combination of a text box in which the user enters an item and a drop-down list from which the user selects an item.
Let's create a combo box by dragging a ComboBox control from the Toolbox and dropping it on the form.

You can populate the list box items either from the properties window or at runtime. To add items to a ListBox, select the ListBox control and get to the properties window, for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line.
Properties of the ComboBox Control
The following are some of the commonly used properties of the ComboBox control:
| S.N | Property | Description |
| 1 | AllowSelection | Gets a value indicating whether the list enables selection of list items. |
| 2 | AutoCompleteCustomSource | Gets or sets a custom System.Collections.Specialized.StringCollection to use when the AutoCompleteSourceproperty is set to CustomSource. |
| 3 | AutoCompleteMode | Gets or sets an option that controls how automatic completion works for the ComboBox. |
| 4 | AutoCompleteSource | Gets or sets a value specifying the source of complete strings used for automatic completion. |
| 5 | DataBindings | Gets the data bindings for the control. |
| 6 | DataManager | Gets the CurrencyManager associated with this control. |
| 7 | DataSource | Gets or sets the data source for this ComboBox. |
| 8 | DropDownHeight | Gets or sets the height in pixels of the drop-down portion of the ComboBox. |
| 9 | DropDownStyle | Gets or sets a value specifying the style of the combo box. |
| 10 | DropDownWidth | Gets or sets the width of the of the drop-down portion of a combo box. |
| 11 | DroppedDown | Gets or sets a value indicating whether the combo box is displaying its drop-down portion. |
| 12 | FlatStyle | Gets or sets the appearance of the ComboBox. |
| 13 | ItemHeight | Gets or sets the height of an item in the combo box. |
| 14 | Items | Gets an object representing the collection of the items contained in this ComboBox. |
| 15 | MaxDropDownItems | Gets or sets the maximum number of items to be displayed in the drop-down part of the combo box. |
| 16 | MaxLength | Gets or sets the maximum number of characters a user can enter in the editable area of the combo box. |
| 17 | SelectedIndex | Gets or sets the index specifying the currently selected item. |
| 18 | SelectedItem | Gets or sets currently selected item in the ComboBox. |
| 19 | SelectedText | Gets or sets the text that is selected in the editable portion of a ComboBox. |
| 20 | SelectedValue | Gets or sets the value of the member property specified by the ValueMember property. |
| 21 | SelectionLength | Gets or sets the number of characters selected in the editable portion of the combo box. |
| 22 | SelectionStart | Gets or sets the starting index of text selected in the combo box. |
| 23 | Sorted | Gets or sets a value indicating whether the items in the combo box are sorted. |
| 24 | Text | Gets or sets the text associated with this control. |
Methods of the ComboBox Control
The following are some of the commonly used methods of the ComboBox control:
| S.N | Method Name & Description |
| 1 | BeginUpdate
Prevents the control from drawing until the EndUpdate method is called, while items are added to the combo box one at a time. |
| 2 | EndUpdate
Resumes drawing of a combo box, after it was turned off by the BeginUpdate method. |
| 3 | FindString
Finds the first item in the combo box that starts with the string specified as an argument. |
| 4 | FindStringExact
Finds the first item in the combo box that exactly matches the specified string. |
| 5 | SelectAll
Selects all the text in the editable area of the combo box. |
Events of the ComboBox Control
The following are some of the commonly used events of the ComboBox control:
| S.N | Event | Description |
| 1 | DropDown | Occurs when the drop-down portion of a combo box is displayed. |
| 2 | DropDownClosed | Occurs when the drop-down portion of a combo box is no longer visible. |
| 3 | DropDownStyleChanged | Occurs when the DropDownStyle property of the ComboBox has changed. |
| 4 | SelectedIndexChanged | Occurs when the SelectedIndex property of a ComboBox control has changed. |
| 5 | SelectionChangeCommitted | Occurs when the selected item has changed and the change appears in the combo box. |
Example
In this example, let us fill a combo box with various items, get the selected items in the combo box and show them in a list box and sort the items.
Drag and drop a combo box to store the items, a list box to display the selected items, four button controls to add to the list box with selected items, to fill the combo box, to sort the items and to clear the combo box list respectively.
Add a label control that would display the selected item.

Add the following code in the code editor window:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
'sends the selected items to the list box
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex > -1 Then
Dim sindex As Integer
sindex = ComboBox1.SelectedIndex
Dim sitem As Object
sitem = ComboBox1.SelectedItem
ListBox1.Items.Add(sitem)
End If
End Sub
'populates the list
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
ComboBox1.Items.Clear()
ComboBox1.Items.Add("Safety")
ComboBox1.Items.Add("Security")
ComboBox1.Items.Add("Governance")
ComboBox1.Items.Add("Good Music")
ComboBox1.Items.Add("Good Movies")
ComboBox1.Items.Add("Good Books")
ComboBox1.Items.Add("Education")
ComboBox1.Items.Add("Roads")
ComboBox1.Items.Add("Health")
ComboBox1.Items.Add("Food for all")
ComboBox1.Items.Add("Shelter for all")
ComboBox1.Items.Add("Industrialisation")
ComboBox1.Items.Add("Peace")
ComboBox1.Items.Add("Liberty")
ComboBox1.Items.Add("Freedom of Speech")
ComboBox1.Text = "Select from..."
End Sub
'sorting the list
Private Sub Button3_Click(sender As Object, e As EventArgs)
ComboBox1.Sorted = True
End Sub
'clears the list
Private Sub Button4_Click(sender As Object, e As EventArgs)
ComboBox1.Items.Clear()
End Sub
'displaying the selected item on the label
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _
Handles ListBox1.SelectedIndexChanged
Label1.Text = ComboBox1.SelectedItem.ToString()
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:

Click on various buttons to check the actions performed by each:

The RadioButton control is used to provide a set of mutually exclusive options. The user can select one radio button in a group. If you need to place more than one group of radio buttons in the same form, you should place them in different container controls like a GroupBox control.
Let's create three radio buttons by dragging RadioButton controls from the Toolbox and dropping on the form.

The Checked property of the radio button is used to set the state of a radio button. You can display text, image or both on radio button control. You can also change the appearance of the radio button control by using theAppearance property.
Properties of the RadioButton Control
The following are some of the commonly used properties of the RadioButton control:
| S.N | Property | Description |
| 1 | Appearance | Gets or sets a value determining the appearance of the radio button. |
| 2 | AutoCheck | Gets or sets a value indicating whether the Checked value and the appearance of the control automatically change when the control is clicked. |
| 3 | CheckAlign | Gets or sets the location of the check box portion of the radio button. |
| 4 | Checked | Gets or sets a value indicating whether the control is checked. |
| 5 | Text | Gets or sets the caption for a radio button. |
| 6 | TabStop | Gets or sets a value indicating whether a user can give focus to the RadioButton control using the TAB key. |
Methods of the RadioButton Control
The following are some of the commonly used methods of the RadioButton control:
| S.N | Method Name & Description |
| 1 | PerformClick
Generates a Click event for the control, simulating a click by a user. |
Events of the RadioButton Control
The following are some of the commonly used events of the RadioButton control:
| S.N | Event | Description |
| 1 | AppearanceChanged | Occurs when the value of the Appearance property of the RadioButton control is changed. |
| 2 | CheckedChanged | Occurs when the value of the Checked property of the RadioButton control is changed. |
Consult Microsoft documentation for detailed list of properties, methods and events of the RadioButton control.
Example
In the following example, let us create two groups of radio buttons and use their CheckedChanged events for changing the BackColor and ForeColor property of the form.

Let's double click on the radio buttons and put the follow code in the opened window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
Private Sub RadioButton1_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton1.CheckedChanged
Me.BackColor = Color.Red
End Sub
Private Sub RadioButton2_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton2.CheckedChanged
Me.BackColor = Color.Green
End Sub
Private Sub RadioButton3_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton3.CheckedChanged
Me.BackColor = Color.Blue
End Sub
Private Sub RadioButton4_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton4.CheckedChanged
Me.ForeColor = Color.Black
End Sub
Private Sub RadioButton5_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton5.CheckedChanged
Me.ForeColor = Color.White
End Sub
Private Sub RadioButton6_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton6.CheckedChanged
Me.ForeColor = Color.Red
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:

The TreeView control is used to display hierarchical representations of items similar to the ways the files and folders are displayed in the left pane of the Windows Explorer. Each node may contain one or more child nodes.
Let's click on a TreeView control from the Toolbox and place it on the form.

Properties of the TreeView Control
The following are some of the commonly used properties of the TreeView control:
| S.N | Property | Description |
| 1 | BackColor | Gets or sets the background color for the control. |
| 2 | BackgroundImage | Gets or set the background image for the TreeView control. |
| 3 | BackgroundImageLayout | Gets or sets the layout of the background image for the TreeView control. |
| 4 | BorderStyle | Gets or sets the border style of the tree view control. |
| 5 | CheckBoxes | Gets or sets a value indicating whether check boxes are displayed next to the tree nodes in the tree view control. |
| 6 | DataBindings | Gets the data bindings for the control. |
| 7 | Font | Gets or sets the font of the text displayed by the control. |
| 8 | FontHeight | Gets or sets the height of the font of the control. |
| 9 | ForeColor | The current foreground color for this control, which is the color the control uses to draw its text. |
| 10 | ItemHeight | Gets or sets the height of each tree node in the tree view control. |
| 11 | Nodes | Gets the collection of tree nodes that are assigned to the tree view control. |
| 12 | PathSeparator | Gets or sets the delimiter string that the tree node path uses. |
| 13 | RightToLeftLayout | Gets or sets a value that indicates whether the TreeView should be laid out from right-to-left. |
| 14 | Scrollable | Gets or sets a value indicating whether the tree view control displays scroll bars when they are needed. |
| 15 | SelectedImageIndex | Gets or sets the image list index value of the image that is displayed when a tree node is selected. |
| 16 | SelectedImageKey | Gets or sets the key of the default image shown when a TreeNode is in a selected state. |
| 17 | SelectedNode | Gets or sets the tree node that is currently selected in the tree view control. |
| 18 | ShowLines | Gets or sets a value indicating whether lines are drawn between tree nodes in the tree view control. |
| 19 | ShowNodeToolTips | Gets or sets a value indicating ToolTips are shown when the mouse pointer hovers over a TreeNode. |
| 20 | ShowPlusMinus | Gets or sets a value indicating whether plus-sign (+) and minus-sign (-) buttons are displayed next to tree nodes that contain child tree nodes. |
| 21 | ShowRootLines | Gets or sets a value indicating whether lines are drawn between the tree nodes that are at the root of the tree view. |
| 22 | Sorted | Gets or sets a value indicating whether the tree nodes in the tree view are sorted. |
| 23 | StateImageList | Gets or sets the image list that is used to indicate the state of the TreeView and its nodes. |
| 24 | Text | Gets or sets the text of the TreeView. |
| 25 | TopNode | Gets or sets the first fully-visible tree node in the tree view control. |
| 26 | TreeViewNodeSorter | Gets or sets the implementation of IComparer to perform a custom sort of the TreeView nodes. |
| 27 | VisibleCount | Gets the number of tree nodes that can be fully visible in the tree view control. |
Methods of the TreeView Control
The following are some of the commonly used methods of the TreeView control:
| S.N | Method Name & Description |
| 1 | CollapseAll
Collapses all the nodes including all child nodes in the tree view control. |
| 2 | ExpandAll
Expands all the nodes. |
| 3 | GetNodeAt
Gets the node at the specified location. |
| 4 | GetNodeCount
Gets the number of tree nodes. |
| 5 | Sort
Sorts all the items in the tree view control. |
| 6 | ToString
Returns a string containing the name of the control. |
Events of the TreeView Control
The following are some of the commonly used events of the TreeView control:
| S.N | Event | Description |
| 1 | AfterCheck | Occurs after the tree node check box is checked. |
| 2 | AfterCollapse | Occurs after the tree node is collapsed. |
| 3 | AfterExpand | Occurs after the tree node is expanded. |
| 4 | AfterSelect | Occurs after the tree node is selected. |
| 5 | BeforeCheck | Occurs before the tree node check box is checked. |
| 6 | BeforeCollapse | Occurs before the tree node is collapsed. |
| 7 | BeforeExpand | Occurs before the tree node is expanded. |
| 8 | BeforeLabelEdit | Occurs before the tree node label text is edited. |
| 9 | BeforeSelect | Occurs before the tree node is selected. |
| 10 | ItemDrag | Occurs when the user begins dragging a node. |
| 11 | NodeMouseClick | Occurs when the user clicks a TreeNode with the mouse. |
| 12 | NodeMouseDoubleClick | Occurs when the user double-clicks a TreeNode with the mouse. |
| 13 | NodeMouseHover | Occurs when the mouse hovers over a TreeNode. |
| 14 | PaddingChanged | Occurs when the value of the Padding property changes. |
| 15 | Paint | Occurs when the TreeView is drawn. |
| 16 | RightToLeftLayoutChanged | Occurs when the value of the RightToLeftLayout property changes. |
| 17 | TextChanged | Occurs when the Text property changes. |
The TreeNode Class
The TreeNode class represents a node of a TreeView. Each node in a TreeView control is an object of the TreeNode class. To be able to use a TreeView control we need to have a look at some commonly used properties and methods of the TreeNode class.
Properties of the TreeNode Class
The following are some of the commonly used properties of the TreeNode class:
| S.N | Property | Description |
| 1 | BackColor | Gets or sets the background color of the tree node. |
| 2 | Checked | Gets or sets a value indicating whether the tree node is in a checked state. |
| 3 | ContextMenu | Gets the shortcut menu that is associated with this tree node. |
| 4 | ContextMenuStrip | Gets or sets the shortcut menu associated with this tree node. |
| 5 | FirstNode | Gets the first child tree node in the tree node collection. |
| 6 | FullPath | Gets the path from the root tree node to the current tree node. |
| 7 | Index | Gets the position of the tree node in the tree node collection. |
| 8 | IsEditing | Gets a value indicating whether the tree node is in an editable state. |
| 9 | IsExpanded | Gets a value indicating whether the tree node is in the expanded state. |
| 10 | IsSelected | Gets a value indicating whether the tree node is in the selected state. |
| 11 | IsVisible | Gets a value indicating whether the tree node is visible or partially visible. |
| 12 | LastNode | Gets the last child tree node. |
| 13 | Level | Gets the zero-based depth of the tree node in the TreeView control. |
| 14 | Name | Gets or sets the name of the tree node. |
| 15 | NextNode | Gets the next sibling tree node. |
| 16 | Nodes | Gets the collection of TreeNode objects assigned to the current tree node. |
| 17 | Parent | Gets the parent tree node of the current tree node. |
| 18 | PrevNode | Gets the previous sibling tree node. |
| 19 | PrevVisibleNode | Gets the previous visible tree node. |
| 20 | Tag | Gets or sets the object that contains data about the tree node. |
| 21 | Text | Gets or sets the text displayed in the label of the tree node. |
| 22 | ToolTipText | Gets or sets the text that appears when the mouse pointer hovers over a TreeNode. |
| 23 | TreeView | Gets the parent tree view that the tree node is assigned to. |
Methods of the TreeNode Class
The following are some of the commonly used methods of the TreeNode class:
| S.N | Method Name & Description |
| 1 | Collapse
Collapses the tree node. |
| 2 | Expand
Expands the tree node. |
| 3 | ExpandAll
Expands all the child tree nodes. |
| 4 | GetNodeCount
Returns the number of child tree nodes. |
| 5 | Remove
Removes the current tree node from the tree view control. |
| 6 | Toggle
Toggles the tree node to either the expanded or collapsed state. |
| 7 | ToString
Returns a string that represents the current object. |
Example
In this example, let us create a tree view at runtime. Let's double click on the Form and put the follow code in the opened window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'create a new TreeView
Dim TreeView1 As TreeView
TreeView1 = New TreeView()
TreeView1.Location = New Point(10, 10)
TreeView1.Size = New Size(150, 150)
Me.Controls.Add(TreeView1)
TreeView1.Nodes.Clear()
'Creating the root node
Dim root = New TreeNode("Application")
TreeView1.Nodes.Add(root)
TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 1"))
'Creating child nodes under the first child
For loopindex As Integer = 1 To 4
TreeView1.Nodes(0).Nodes(0).Nodes.Add(New _
TreeNode("Sub Project" & Str(loopindex)))
Next loopindex
' creating child nodes under the root
TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 6"))
'creating child nodes under the created child node
For loopindex As Integer = 1 To 3
TreeView1.Nodes(0).Nodes(1).Nodes.Add(New _
TreeNode("Project File" & Str(loopindex)))
Next loopindex
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:

You can expand the nodes to see the child nodes:

The ListView control is used to display a list of items. Along with the TreeView control, it allows you to create a Windows Explorer like interface.
Let's click on a ListView control from the Toolbox and place it on the form.

The ListView control displays a list of items along with icons. The Item property of the ListView control allows you to add and remove items from it. The SelectedItem property contains a collection of the selected items. The MultiSelectproperty allows you to set select more than one item in the list view. The CheckBoxes property allows you to set check boxes next to the items.
Properties of the ListView Control
The following are some of the commonly used properties of the ListView control:
| S.N | Property | Description |
| 1 | Alignment | Gets or sets the alignment of items in the control. |
| 2 | AutoArrange | Gets or sets whether icons are automatically kept arranged. |
| 3 | BackColor | Gets or sets the background color. |
| 4 | CheckBoxes | Gets or sets a value indicating whether a check box appears next to each item in the control. |
| 5 | CheckedIndices | Gets the indexes of the currently checked items in the control. |
| 6 | CheckedItems | Gets the currently checked items in the control. |
| 7 | Columns | Gets the collection of all column headers that appear in the control. |
| 8 | GridLines | Gets or sets a value indicating whether grid lines appear between the rows and columns containing the items and subitems in the control. |
| 9 | HeaderStyle | Gets or sets the column header style. |
| 10 | HideSelection | Gets or sets a value indicating whether the selected item in the control remains highlighted when the control loses focus. |
| 11 | HotTracking | Gets or sets a value indicating whether the text of an item or subitem has the appearance of a hyperlink when the mouse pointer passes over it. |
| 12 | HoverSelection | Gets or sets a value indicating whether an item is automatically selected when the mouse pointer remains over the item for a few seconds. |
| 13 | InsertionMark | Gets an object used to indicate the expected drop location when an item is dragged within a ListView control. |
| 14 | Items | Gets a collection containing all items in the control. |
| 15 | LabelWrap | Gets or sets a value indicating whether item labels wrap when items are displayed in the control as icons. |
| 16 | LargeImageList | Gets or sets the ImageList to use when displaying items as large icons in the control. |
| 17 | MultiSelect | Gets or sets a value indicating whether multiple items can be selected. |
| 18 | RightToLeftLayout | Gets or sets a value indicating whether the control is laid out from right to left. |
| 19 | Scrollable | Gets or sets a value indicating whether a scroll bar is added to the control when there is not enough room to display all items. |
| 20 | SelectedIndices | Gets the indexes of the selected items in the control. |
| 21 | SelectedItems | Gets the items that are selected in the control. |
| 22 | ShowGroups | Gets or sets a value indicating whether items are displayed in groups. |
| 23 | ShowItemToolTips | Gets or sets a value indicating whether ToolTips are shown for the ListViewItem objects contained in theListView. |
| 24 | SmallImageList | Gets or sets the ImageList to use when displaying items as small icons in the control. |
| 25 | Sorting | Gets or sets the sort order for items in the control. |
| 26 | StateImageList | Gets or sets the ImageList associated with application-defined states in the control. |
| 27 | TopItem | Gets or sets the first visible item in the control. |
| 28 | View | Gets or sets how items are displayed in the control. This property has the following values:
- LargeIcon - displays large items with a large 32 x 32 pixels icon.
- SmallIcon - displays items with a small 16 x 16 pixels icon
- List - displays small icons always in one column
- Details - displays items in multiple columns with column headers and fields
- Tile - displays items as full-size icons with item labels and sub-item information.
|
| 29 | VirtualListSize | Gets or sets the number of ListViewItem objects contained in the list when in virtual mode. |
| 30 | VirtualMode | Gets or sets a value indicating whether you have provided your own data-management operations for the ListView control. |
Methods of the ListView Control
The following are some of the commonly used methods of the ListView control:
| S.N | Method Name & Description |
| 1 | Clear
Removes all items from the ListView control. |
| 1 | ToString
Returns a string containing the string representation of the control. |
Events of the ListView Control
The following are some of the commonly used events of the ListView control:
| S.N | Event | Description |
| 1 | ColumnClick | Occurs when a column header is clicked. |
| 2 | ItemCheck | Occurs when an item in the control is checked or unchecked. |
| 3 | SelectedIndexChanged | Occurs when the selected index is changed. |
| 4 | TextChanged | Occurs when the Text property is changed. |
Example
In this example, let us create a list view at runtime. Let's double click on the Form and put the follow code in the opened window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'create a new ListView
Dim ListView1 As ListView
ListView1 = New ListView()
ListView1.Location = New Point(10, 10)
ListView1.Size = New Size(150, 150)
Me.Controls.Add(ListView1)
'Creating the list items
Dim ListItem1 As ListViewItem
ListItem1 = ListView1.Items.Add("Item 1")
Dim ListItem2 As ListViewItem
ListItem2 = ListView1.Items.Add("Item 2")
Dim ListItem3 As ListViewItem
ListItem3 = ListView1.Items.Add("Item 3")
Dim ListItem4 As ListViewItem
ListItem4 = ListView1.Items.Add("Item 4")
'set the view property
ListView1.View = View.SmallIcon
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
