What Is Event-Driven Programming?: COMP314/ACMP312/BIT201
What Is Event-Driven Programming?: COMP314/ACMP312/BIT201
The diagram below illustrates the relationship between events, the scheduler, and the
application’s event-handlers.
Event-driven programming depends upon an event loop that is always listening for the
new incoming events. The working of event-driven programming is dependent upon
events. Once an event loops, then events decide what to execute and in what order.
Following flowchart will help you understand how this works.
1
Introduction to VB.Net
2
It is not a case sensitive language, whereas, C++, Java, and C# are case sensitive
language.
Features of VB.net
3
It provides simple events management in .NET application.
A Window Form enables us to inherit all existing functionality of form that
can be used to create a new form. So, in this way, it reduced the code
complexity.
It uses an external object as a reference that can be used in a VB.NET
application.
However, these features are not available in the previous version of Visual
Basic 6. That’s why Microsoft launched VB.NET language.
3. Using the Visual Studio IDE, you can develop a small program that works
faster, with a large desktop and web application.
4. The .NET Framework is a software framework that has a large collection
of libraries, which helps in developing more robust applications.
5. It uses drop and drag elements to create web forms in .NET applications.
6. However, a Visual Basic .NET allows to connect one application to another
application that created in the same language to run on the .NET
framework.
7. A VB.NET can automatically structure your code.
8. The Visual Basic .NET language is also used to transfer data between
different layers of the .NET architecture such that data is passed as simple
text strings.
9. It uses a new concept of error handling in the Visual Basic .NET
Framework. The new structure is the try, catch, and finally method used to
handle exceptions as a unit.
4
In addition, it allows appropriate action to be taken at the place where it
encountered an error. In this way, it discourages the use of the ON ERROR
GOTO statement in .NET programming.
Disadvantages of VB.net Programming
Furthermore, additional coding takes extra CPU cycles that increases the
processing time. It shows the slowness of the VB.NET application.
It means that the target computer needs a JIT compiler to interpret a source
program in IL, and this interpretation requires an additional CPU cycle that
degrades the performance of an application.
5. It contains a large collection of libraries for the JIT compiler that helps to
interpret an application. These large libraries hold a vast space in our system
that takes more computing time.
5
VB.Net - Program Structure
Before we study basic building blocks of the VB.Net programming language, let us
look a bare minimum VB.Net program structure so that we can take it as a
reference in upcoming chapters.
Imports System
Module Module1
'This program will display Hello World
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Hello, World!
6
Classes or Modules generally would contain more than one procedure.
Procedures contain the executable code, or in other words, they define the
behavior of the class. A procedure could be any of the following −
o Function
o Sub
o Operator
o Get
o Set
o AddHandler
o RemoveHandler
o RaiseEvent
The next line ('This program) will be ignored by the compiler and it has been
put to add additional comments in the program.
The next line defines the Main procedure, which is the entry point for all
VB.Net programs. The Main procedure states what the module or class will
do when executed.
The Main procedure specifies its behavior with the statement
Console.WriteLine("Hello World") WriteLine is a method of
the Console class defined in the System namespace. This statement causes
the message "Hello, World!" to be displayed on the screen.
The last line Console.ReadKey() is for the VS.NET Users. This will prevent
the screen from running and closing quickly when the program is launched
from Visual Studio .NET.
If you are using Visual Studio.Net IDE, take the following steps −
Start Visual Studio.
On the menu bar, choose File → New → Project.
Choose Visual Basic from templates
Choose Console Application.
Specify a name and location for your project using the Browse button, and
then choose the OK button.
The new project appears in Solution Explorer.
Write code in the Code Editor.
Click the Run button or the F5 key to run the project. A Command Prompt
window appears that contains the line Hello World.
You can compile a VB.Net program by using the command line instead of the
Visual Studio IDE −
7
Open a text editor and add the above mentioned code.
Save the file as helloworld.vb
Open the command prompt tool and go to the directory where you saved the
file.
Type vbc helloworld.vb and press enter to compile your code.
If there are no errors in your code the command prompt will take you to the
next line and would generate helloworld.exe executable file.
Next, type helloworld to execute your program.
You will be able to see "Hello World" printed on the screen.
8
VB.Net - Basic Syntax
VB.Net is an object-oriented programming language. In Object-Oriented
Programming methodology, a program consists of various objects that interact with
each other by means of actions. The actions that an object may take are called
methods. Objects of the same kind are said to have the same type or, more often,
are said to be in the same class.
When we consider a VB.Net program, it can be defined as a collection of objects
that communicate via invoking each other's methods. Let us now briefly look into
what do class, object, methods and instance variables mean.
Object − Objects have states and behaviors. Example: A dog has states -
color, name, breed as well as behaviors - wagging, barking, eating, etc. An
object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the
behaviors/states that objects of its type support.
Methods − A method is basically a behavior. A class can contain many
methods. It is in methods where the logics are written, data is manipulated
and all the actions are executed.
Instance Variables − Each object has its unique set of instance variables.
An object's state is created by the values assigned to these instance variables.
For example, let us consider a Rectangle object. It has attributes like length and
width. Depending upon the design, it may need ways for accepting the values of
these attributes, calculating area and displaying details.
Let us look at an implementation of a Rectangle class and discuss VB.Net basic
syntax on the basis of our observations in it −
Imports System
Public Class Rectangle
Private length As Double
Private width As Double
'Public methods
Public Sub AcceptDetails()
length = 4.5
width = 3.5
End Sub
9
Public Function GetArea() As Double
GetArea = length * width
End Function
Public Sub Display()
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
End Sub
In previous chapter, we created a Visual Basic module that held the code. Sub
Main indicates the entry point of VB.Net program. Here, we are using Class that
contains both code and data. You use classes to create objects. For example, in the
code, r is a Rectangle object.
An object is an instance of a class −
Dim r As New Rectangle()
A class may have members that can be accessible from outside class, if so
specified. Data members are called fields and procedure members are called
methods.
Shared methods or static methods can be invoked without creating an object of
the class. Instance methods are invoked through an object of the class −
Shared Sub Main()
Dim r As New Rectangle()
10
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub
Identifiers
VB.Net Keywords
11
Namesp
ace
12
13
VB.Net - Variables
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in VB.Net has a specific type, which determines the size
and layout of the variable's memory; the range of values that can be stored within
that memory; and the set of operations that can be applied to the variable.
We have already discussed various data types. The basic value types provided in
VB.Net can be categorized as −
Type Example
VB.Net also allows defining other value types of variable like Enum and reference
types of variables like Class. We will discuss date types and Classes in subsequent
chapters.
The Dim statement is used for variable declaration and storage allocation for one
or more variables. The Dim statement is used at module, class, structure, procedure
or block level.
Syntax for variable declaration in VB.Net is −
[ < attributelist > ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]]
[ ReadOnly ] Dim [ WithEvents ] variablelist
Where,
attributelist is a list of attributes that apply to the variable. Optional.
14
accessmodifier defines the access levels of the variables, it has values as -
Public, Protected, Friend, Protected Friend and Private. Optional.
Shared declares a shared variable, which is not associated with any specific
instance of a class or structure, rather available to all the instances of the
class or structure. Optional.
Shadows indicate that the variable re-declares and hides an identically
named element, or set of overloaded elements, in a base class. Optional.
Static indicates that the variable will retain its value, even when the after
termination of the procedure in which it is declared. Optional.
ReadOnly means the variable can be read, but not written. Optional.
WithEvents specifies that the variable is used to respond to events raised by
the instance assigned to the variable. Optional.
Variablelist provides the list of variables declared.
Each variable in the variable list has the following syntax and parts −
variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]
Where,
variablename − is the name of the variable
boundslist − optional. It provides list of bounds of each dimension of an
array variable.
New − optional. It creates a new instance of the class when the Dim
statement runs.
datatype − Required if Option Strict is On. It specifies the data type of the
variable.
initializer − Optional if New is not specified. Expression that is evaluated
and assigned to the variable when it is created.
Some valid variable declarations along with their definition are shown here −
Dim StudentID As Integer
Dim StudentName As String
Dim Salary As Double
Dim count1, count2 As Integer
Dim status As Boolean
Dim exitButton As New System.Windows.Forms.Button
Dim lastTime, nextTime As Date
15
Variables are initialized (assigned a value) with an equal sign followed by a
constant expression. The general form of initialization is −
variable_name = value;
for example,
Dim pi As Double
pi = 3.14159
You can initialize a variable at the time of declaration as follows −
Dim StudentID As Integer = 100
Dim StudentName As String = "Bill Smith"
Example
Try the following example which makes use of various types of variables −
Module variablesNdataypes
Sub Main()
Dim a As Short
Dim b As Integer
Dim c As Double
a = 10
b = 20
c=a+b
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a = 10, b = 20, c = 30
The Console class in the System namespace provides a function ReadLine for
accepting input from the user and store it into a variable. For example,
Dim message As String
16
message = Console.ReadLine
The following example demonstrates it −
Module variablesNdataypes
Sub Main()
Dim message As String
Console.Write("Enter message: ")
message = Console.ReadLine
Console.WriteLine()
Console.WriteLine("Your Message: {0}", message)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result
(assume the user inputs Hello World) −
Enter message: Hello World
Your Message: Hello World
17
Classes and Objects in VB.net
The Classes and Objects in VB.net are interrelated. Each Object in VB.net is
defined by a Class. A Class in VB.net describes
the variables, properties, procedures, and events of an object. Objects are
instances of classes; you can create as many objects you need once you have
defined a class.
To understand the relationship between an object and its class, think of cookie
cutters and cookies. The cookie cutter is the class. It defines the characteristics of
each cookie, for example size and shape. The class is used to create objects. The
objects are the cookies.
Here is an example that will help you to clarify the above points. Suppose we have
a class called “CAR“. All CAR have bodies, engines etc. and these could be the
attributes (properties) of our CAR class.
So, the idea you really want to enforce in your own mind is that the ‘template’ of
a CAR does not change. Each Object was built from the same set of template
(Class) and therefore contains the same components.
All Objects share the same copy of the member functions (methods), but
maintain a separate copy of the member data (Properties). For example:
A Ferrari Car and a Audi Car are both Cars, so they can be classified as
belonging to the Car class. All have same movement (methods) but different in
models (properties).
18
and functions will be included in a class object. For instance, it represents the
variable and method that will operate on the class object.
1. attributelist
4. MustInherit
MustInherit makes it clear that the class, which is an abstract class, can only be
used as a base class and cannot be used to directly construct objects.
5. NotInheritable
6. Partial
Partial denotes that the class has only been partially defined.
7. Inherits
8. Implements
The interfaces from which the class derives are specified in implements.
19
Using Classes in VB.net
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
'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
20
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
21
Functions in VB.net
The functions in VB.net is a separate group of codes that are used to perform a
specific task when the defined function is called in a program. After the
execution of a function, control transfer to the main() method for further
execution. It returns a value.
[Statements]
End Function
1. Modifiers
2. FunctionName
3. ParameterList
4. ReturnType
22
The function FindMax in the following code snippet returns the greater of two
integer values given two values.
In VB.Net, a function has two different ways to return a value to the caller code.
23
VB.Net - Sub Procedures
As we mentioned in the previous chapter, Sub procedures are procedures that do
not return any value. We have been using the Sub procedure Main in all our
examples. We have been writing console applications so far in these tutorials.
When these applications start, the control goes to the Main Sub procedure, and it in
turn, runs any other statements constituting the body of the program.
The Sub statement is used to declare the name, parameter and the body of a sub
procedure. The syntax for the Sub statement is −
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
Modifiers − specify the access level of the procedure; possible values are -
Public, Private, Protected, Friend, Protected Friend and information
regarding overloading, overriding, sharing, and shadowing.
SubName − indicates the name of the Sub
ParameterList − specifies the list of the parameters
Example
The following example demonstrates a Sub procedure CalculatePay that takes two
parameters hours and wages and displays the total pay of an employee −
Module mysub
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
CalculatePay(25, 10)
CalculatePay(40, 20)
CalculatePay(30, 27.5)
24
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Total Pay: $250.00
Total Pay: $800.00
Total Pay: $825.00
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
25
When the above code is compiled and executed, it produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there is no change in the values though they had been changed inside
the function.
Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
26
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
27
VB.Net - Exception Handling
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
28
Exception Classes in .Net Framework
29
Handling Exceptions
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
You can also define your own exception. User-defined exception classes are
derived from the ApplicationException 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
30
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
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()
31
End Sub
End Module
32
VB.Net - File Handling
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).
The System.IO namespace has various classes that are used for performing various
operations 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 −
33
StreamReader Used for reading characters from a byte stream.
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 a FileStream 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("sample.txt", FileMode.OpenOrCreate,
FileAccess.ReadWrite)
Parameter Description
34
FileAccess FileAccess enumerators have
members: Read, ReadWrite and Write.
Example
Imports System.IO
Module fileProg
Sub Main()
Dim f1 As FileStream = New FileStream("sample.txt", _
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 the following result −
35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
36
VB.Net - Basic Controls
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 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 Window. 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
37
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
Basic Controls
38
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
the System.Windows.Forms namespace.
The following table lists some of the commonly used controls −
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.
39
8 CheckBox
It 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.
40
Decision Making and Looping
Decision making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most
of the programming languages −
VB.Net provides the following types of decision making statements. Click the
following links to check their details.
Statement Description
41
nested If statements You can use one If or Else if statement inside
another If or Else if statement(s).
nested Select Case You can use one select case statement inside
statements another select case statement(s).
Looping
There may be a situation when you need to execute a block of code several number
of times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times and following is the general form of a loop statement in most of the
programming languages −
42
VB.Net provides following types of loops to handle looping requirements. Click
the following links to check their details.
Nested loops You can use one or more loops inside any another
While, For or Do loop.
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
43
VB.Net provides the following control statements. Click the following links to
check their details.
Continue statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
44
VB.Net - Database Access
Applications communicate with a database, firstly, to retrieve the data stored there
and present it in a user-friendly way, and secondly, to update the database by
inserting, modifying and deleting data.
Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net
framework that is used by the .Net applications for retrieving, accessing and
updating data.
ADO.Net object model is nothing but the structured process flow through various
components. The object model can be pictorially described as −
The data residing in a data store or database is retrieved through the data
provider. Various components of the data provider retrieve data for the application
and update data.
An application accesses data either through a dataset or a data reader.
Datasets store data in a disconnected cache and the application retrieves data
from it.
Data readers provide data to the application in a read-only and forward-only
mode.
45
Data Provider
1 Connection
This component is used to set up a connection with a data source.
2 Command
A command is a SQL statement or a stored procedure used to
retrieve, insert, delete or modify data in a data source.
3 DataReader
Data reader is used to retrieve data from a data source in a read-only
and forward-only mode.
4 DataAdapter
This is integral to the working of ADO.Net since data is transferred
to and from a database through a data adapter. It retrieves data from
a database into a dataset and updates the database. When changes
are made to the dataset, the changes in the database are actually
done by the data adapter.
46
The .Net Framework data provider for ODBC - provides access to data
sources exposed by ODBC.
The .Net Framework data provider for Oracle - provides access to Oracle
data source.
The EntityClient provider - enables accessing data through Entity Data
Model (EDM) applications.
DataSet
The DataSet class is present in the System.Data namespace. The following table
describes all the components of DataSet −
47
Sr.No Components & Description
.
1 DataTableCollection
It contains all the tables retrieved from the data source.
2 DataRelationCollection
It contains relationships and the links between tables in a data set.
3 ExtendedProperties
It contains additional information, like the SQL statement for
retrieving data, time of retrieval, etc.
4 DataTable
It represents a table in the DataTableCollection of a dataset. It
consists of the DataRow and DataColumn objects. The DataTable
objects are case-sensitive.
5 DataRelation
It represents a relationship in the DataRelationshipCollection of the
dataset. It is used to relate two DataTable objects to each other
through the DataColumn objects.
6 DataRowCollection
It contains all the rows in a DataTable.
7 DataView
It represents a fixed customized view of a DataTable for sorting,
filtering, searching, editing and navigation.
8 PrimaryKey
48
It represents the column that uniquely identifies a row in a
DataTable.
9 DataRow
It represents a row in the DataTable. The DataRow object and its
properties and methods are used to retrieve, evaluate, insert, delete,
and update values in the DataTable. The NewRow method is used to
create a new row and the Add method adds a row to the table.
10 DataColumnCollection
It represents all the columns in a DataTable.
11 DataColumn
It consists of the number of columns that comprise a DataTable.
Connecting to a Database
Example 1
49
Select a server name and the database name in the Add Connection dialog box.
50
51
Add a DataGridView on the form.
52
Choose DataSet as the database model.
Save the connection string.
53
Choose the database object, Customers table in our example, and click the
Finish button.
Select the Preview Data link to see the data in the Results grid −
54
When the application is run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window
Example 2
In this example, let us access data in a DataGridView control using code. Take the
following steps −
Add a DataGridView control and a button in the form.
Change the text of the button control to 'Fill'.
Double click the button control to add the required code for the Click event
of the button, as shown below −
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
'TODO: This line of code loads data into the 'TestDBDataSet.CUSTOMERS'
table.
55
You can move, or remove it, as needed.
Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim connection As SqlConnection = New sqlconnection()
connection.ConnectionString = "Data Source=KABIR-DESKTOP; _
Initial Catalog=testDB;Integrated Security=True"
connection.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter _
("select * from Customers", connection)
Dim ds As DataSet = New DataSet()
adp.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
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 the following window −
56
Clicking the Fill button displays the table on the data grid view control −
We have discussed that the DataSet components like DataTable, DataColumn and
DataRow allow us to create tables, columns and rows, respectively.
The following example demonstrates the concept −
Example 3
So far, we have used tables and databases already existing in our computer. In this
example, we will create a table, add columns, rows and data into it and display the
table using a DataGridView object.
Take the following steps −
Add a DataGridView control and a button in the form.
Change the text of the button control to 'Fill'.
Add the 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.
57
Me.Text = "tutorialspont.com"
End Sub
Private Function CreateDataSet() As DataSet
'creating a DataSet object for tables
Dim dataset As DataSet = New DataSet()
' creating the student table
Dim Students As DataTable = CreateStudentTable()
dataset.Tables.Add(Students)
Return dataset
End Function
Private Function CreateStudentTable() As DataTable
Dim Students As DataTable
Students = New DataTable("Student")
' adding columns
AddNewColumn(Students, "System.Int32", "StudentID")
AddNewColumn(Students, "System.String", "StudentName")
AddNewColumn(Students, "System.String", "StudentCity")
' adding rows
AddNewRow(Students, 1, "Zara Ali", "Kolkata")
AddNewRow(Students, 2, "Shreya Sharma", "Delhi")
AddNewRow(Students, 3, "Rini Mukherjee", "Hyderabad")
AddNewRow(Students, 4, "Sunil Dubey", "Bikaner")
AddNewRow(Students, 5, "Rajat Mishra", "Patna")
Return Students
End Function
Private Sub AddNewColumn(ByRef table As DataTable, _
ByVal columnType As String, ByVal columnName As String)
Dim column As DataColumn = _
table.Columns.Add(columnName, Type.GetType(columnType))
End Sub
58
newrow("StudentCity") = city
table.Rows.Add(newrow)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim ds As New DataSet
ds = CreateDataSet()
DataGridView1.DataSource = ds.Tables("Student")
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 the following window −
Clicking the Fill button displays the table on the data grid view control −
59
60
VB.Net User Defined Functions
The source code to create a user-defined function to add two integer numbers is given below.
The given program is compiled and executed successfully.
Module Module1
Function AddNum(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
Dim num3 As Integer = 0
Sub Main()
Dim num1 As Integer = 0
Dim num2 As Integer = 0
Dim num3 As Integer = 0
End Module
Enter number1:
20
Enter number2:
30
Addition is: 50
Press any key to continue . . .
Explanation:
In the above program, we created a module Module1 that contains a sub routine Main() and a
user define function AddNum().
61
The Main() subroutine is the entry point for the program. Here, we read two integer numbers
from the user and pass them into AddNum() function.
The AddNum() is the user-defined function that accepts two integer arguments and returns the
addition of arguments to the Main() subroutine, then the output will be printed on the console
screen.
VB.Net Program to Demonstrate the Pass by Reference Mechanism in User Defined Sub-
Routine
Here, we will create a user define sub-routine that will accept two arguments as a pass by
reference. The modification in the pass by reference arguments will also reflect in the calling
function or sub-routine.
Program/Source Code:
The source code to demonstrate the pass by reference mechanism in user define sub-routine is
given below. The given program is compiled and executed successfully.
Module Module1
Sub Swap(ByRef num1 As Integer, ByRef num2 As Integer)
Dim num3 As Integer = 0
num3 = num1
num1 = num2
num2 = num3
Sub Main()
Dim num1 As Integer = 0
Dim num2 As Integer = 0
62
num2 = Integer.Parse(Console.ReadLine())
Swap(num1, num2)
Console.WriteLine("Values outside the sub-routine:")
Console.WriteLine("Num1: {0}", num1)
Console.WriteLine("Num2: {0}", num2)
End Sub
End Module
Output:
Enter number1:
10
Enter number2:
20
Values inside the sub-routine:
Num1: 20
Num2: 10
Explanation:
In the above program, we created a module Module1 that contains two sub-
routines Main() and Swap().
The Main() subroutine is the entry point for the program. Here we read two integer numbers
from the user and pass them into the Swap() sub-routine.
The Swap() is the user-defined subroutine. Here we pass two arguments using pass by reference
mechanism. To use the pass by reference mechanism we need to use the ByRef keyword. In this
sub-routine, we exchange the values of arguments and print them on the console screen. The
modification in arguments also reflects outside the sub-routine.
63
VB.NET PROGRAM TO IMPLEMENT SOCKET SERVER TO ACCEPT CLIENT
CONNECTIONS
Here, we will implement a socket server, which is used to accept connections from different
socket clients and establish communication among them, and then we can send or receive data in
a network.
Program/Source Code:
The source code to implement the socket server to accept client connections is given below.
The given program is compiled and executed successfully.
Imports System
Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Module Module1
Sub Main()
Dim IP As String = "127.0.0.1"
Dim PORT As Integer = 15001
Dim len As Integer = 0
listner.Start()
64
Skt = listner.AcceptSocket()
len = Skt.Receive(byteArray)
Console.WriteLine("Received Data...")
For i = 0 To len - 1 Step 1
Console.Write(Convert.ToChar(byteArray(i)))
Next
Skt.Close()
listner.Stop()
End Sub
End Module
Output:
65
Explanation:
In the above program, we created a socket server on the localhost with a 15001 port. Here, the
server is listening to accept client connections and receive data from the server and send data to
the server. To test the program, here we used the most common network test utility (Hercules),
then we connect to our server using Hercules and send data "Hello" using Hercules then our
server program sends acknowledge data "I have received data" message to the Hercules tool.
Here, we will implement a socket client that will connect to the socket server according to the
given IP address and port number. Then we can communicate to the server and send and receive
data.
Program/Source Code:
The source code to implement the socket client is given below. The given program is compiled
and executed successfully.
Imports System.Text
Imports System.Net.Sockets
Imports System.IO
Module Module1
Sub Main()
Dim client As New TcpClient()
Dim Encoding As New ASCIIEncoding()
Console.WriteLine("Connecting.....")
66
client.Connect("127.0.0.1", 15001)
Console.WriteLine("Connected to server")
strm = client.GetStream()
sendByteArray = Encoding.GetBytes(sendStr)
strm.Write(sendByteArray, 0, sendByteArray.Length)
Console.WriteLine("Data send...")
client.Close()
Console.WriteLine()
End Sub
End Module
Output:
Connecting.....
Connected to server
Data send...
data received
Press any key to continue . . .
67
Explanation:
In the above program, we created a socket server on the localhost with a 15001 port. Here, the
server is listening to accept client connections and receive data from the server and send data to
the server. To test the program, here we used the most common network test utility (Hercules),
then we connect to our server using Hercules and send data "Hello" using Hercules then our
server program sends acknowledge data "I have received data" message to the Hercules tool.
Here, we will read text data from the user and write it into a text file using
the WriteAllText() method of the File class.
Program/Source Code:
The source code to write data into a text file is given below. The given program is compiled
and executed successfully.
68
Imports System.IO
Module Module1
Sub Main()
Dim str As String = Nothing
File.WriteAllText("sample.txt", str)
Console.WriteLine("File Creation Done")
End Sub
End Module
Output:
Explanation:
In the above program, we created a module Module1 that contains the Main() function.
The Main() function is the entry point for the program. And, we created a local variable str of
string type. After that read the value of the str variable from the user and then write data into
the "sample.txt" file using WriteAllText() method of the File class.
Here, we will read data from a text file using ReadAllText() method of the File class. If the
specified file does not exist in the system then a FileNotFoundException gets generated.
Program/Source Code:
The source code to read data from a text file is given below. The given program is compiled
and executed successfully.
Imports System.IO
69
Module Module1
Sub Main()
Dim str As String = Nothing
Try
str = File.ReadAllText("sample.txt")
Console.WriteLine("Content of file: {0}", str)
Catch ex As FileNotFoundException
Console.WriteLine("File does not exist")
End Try
End Sub
End Module
Output:
Explanation:
In the above program, we created a module Module1 that contains the Main() function.
The Main() function is the entry point for the program. And, we created a local variable str of
string type. After that read data from the "sample.txt" text file and print data on the console
screen. If a specified file does not exist in the computer system then a file not found exception
gets generated and prints an appropriate message on the console screen.
Here, we will read data from the text file and then read data from the user and append to the file
using AppendAllText() method of File class.
Program/Source Code:
The source code to append text into the already existing file is given below. The given
program is compiled and executed successfully.
Imports System.IO
Module Module1
Sub Main()
70
Dim str As String = Nothing
Try
str = File.ReadAllText("sample.txt")
File.AppendAllText("sample.txt", str)
Catch ex As FileNotFoundException
Console.WriteLine("File does not exist")
End Try
End Sub
End Module
Output:
Explanation:
In the above program, we created a module Module1 that contains the Main() function.
The Main() function is the entry point for the program. And, we created a local variable str of
string type. After that read data from the "sample.txt" text file and then read data from the user
and append data to the file using AppendAllText() method of File class. If the specified file does
not exist in the computer system then a file not found exception gets generated and prints the
appropriate message on the console screen.
71
VB.Net Program to Delete a Specified File
Here, we will use the Delete() method of the File class to delete the file from the system.
Program/Source Code:
The source code to delete a specified file is given below. The given program is compiled and
executed successfully.
Imports System.IO
Module Module1
Sub Main()
Try
File.Delete("demo.txt")
Catch ex As FileNotFoundException
Console.WriteLine("File does not exist")
End Try
End Sub
End Module
Output:
Explanation:
In the above program, we created a module Module1 that contains the Main() function.
The Main() function is the entry point for the program. And, we deleted the "demo.txt" file
using Delete() method of the File class.
If the specified file does not exist in the computer system then a file not found exception gets
generated and prints the appropriate message on the console screen.
72
VB.NET PROGRAM TO COMPARE TWO STRINGS
Here, we will read two strings and compare using equal to = operator and print the appropriate
message on the console screen.
Program/Source Code:
The source code to compare two strings is given below. The given program is compiled and
executed successfully.
Module Module1
Sub Main()
Dim str1 As String
Dim str2 As String
End Module
Output:
Explanation:
In the above program, we created a module Module1 that contains a method Main(). In
the Main() method, we created two string variables str1 and str2.
73
Console.Write("Enter string1: ")
str1 = Console.ReadLine()
In the above code we use if statements to compare two strings, and then we printed appropriate
message on the console screen.
Program/Source Code:
The source code to check a string is empty or not using IsNothing() function is given below.
The given program is compiled and executed successfully.
Module Module1
Sub Main()
Dim name As String
Dim ret As Boolean
ret = IsNothing(name)
74
End Module
Output:
Explanation:
In the above program, we created a module Module1 that contains a Main() function.
The Main() function is the entry point for the program. Here, we created a variable of string type,
and then check the value of the string is empty or not. Then print an appropriate message on the
console screen.
Here, we will create an array of integers and then read elements from the user, after that print the
elements on the console screen.
Program/Source Code:
The source code to demonstrate the integer array is given below. The given program is
compiled and executed successfully.
Module Module1
Sub Main()
Dim arr As Integer() = New Integer(5) {}
Dim i As Integer = 0
75
Console.WriteLine("Array elements are: ")
For i = 0 To 4 Step 1
Console.Write("{0} ", arr(i))
Next
Console.WriteLine()
End Sub
End Module
Output:
Explanation:
In the above program, we created a module Module1 that contains a function Main(). In
the Main() we created an array arr of five elements.
In the above code, we read the elements of the array from the user.
76
Console.Write("{0} ", arr(i))
Next
Console.WriteLine()
VB.Net Program to Find the Largest Element from the Array of Integers
Here, we will create an array of integers and then read elements from the user after that find the
largest element from the array and print the biggest element on the console screen.
Program/Source Code:
The source code to find the largest element from the array of integers is given below. The
given program is compiled and executed successfully.
Module Module1
Sub Main()
77
End Sub
End Module
Output:
Explanation:
In the above program, we created a module Module1 that contains a function Main().
In the Main() we created an array arr of five elements and an integer variable large, which is
initialized with 0.
In the above code, we read the elements of an array from the user and find the largest element by
comparing each element and update the value of the variable, if we found an element larger than
variable large then we found the largest element in variable large and then print the largest
element on the console screen.
78
VB.Net Program to Find the EVEN Numbers from the Array of Integers
Here, we will create an array of integers and then read elements from the user, after that we will
find the EVEN numbers from the array and print them on the console screen.
Program/Source Code:
The source code to find the EVEN numbers from the array of integers is given below. The
given program is compiled and executed successfully.
Module Module1
Sub Main()
Dim arr As Integer() = New Integer(5) {}
79
End Module
Output:
Explanation:
In the above program, we created a module Module1 that contains a function Main().
In the above code, we read the elements of the array from the user.
In the above code, we found the EVEN numbers from the array and then print them on the
console screen.
80
VB.Net Database Connectivity |Code
Imports System.Data.SqlClient
Public Class IUDS_VB_SQL
Dim con As New SqlConnection("server = hp;database=students;integrated
security=SSPI")
Private Sub InsertButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles InsertButton.Click
Dim insertquery As String = "insert into class
(st_name,address,Roll_No,Email) values(' " & nameTextbox.Text.Trim() & " ','"
& addressTextbox.Text.Trim() & " ','" & rollnoTextbox.Text.Trim() & "','" &
emailTextbox.Text.Trim() & "')"
executequery(insertquery)
'MessageBox.Show("Record inserted successfully", "Welcome...",
MessageBoxButtons.OK, MessageBoxIcon.Information)
lblmessage.Text = "Record inserted successfully"
End Sub
Public Sub executequery(ByVal query As String)
Dim cmd As New SqlCommand(query, con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Sub
Public Sub clear()
nameTextbox.Text = ""
addressTextbox.Text = ""
rollnoTextbox.Text = ""
emailTextbox.Text = ""
idTextbox.Text = ""
lblmessage.Text = ""
idTextbox.Focus()
End Sub
Private Sub DelButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles DelButton.Click
Dim delquery As String = "delete from class where id='" &
idTextbox.Text.Trim() & "'"
executequery(delquery)
lblmessage.Text = "Record Deleted successfully"
clear()
End Sub
Private Sub updateButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles updateButton.Click
81
Dim updatequery As String = "update class set st_name='" &
nameTextbox.Text.Trim() & "',address='" & addressTextbox.Text.Trim() &
"',roll_no='" & rollnoTextbox.Text.Trim() & "',email='" &
emailTextbox.Text.Trim() & "' where id='" & idTextbox.Text.Trim() & "'"
executequery(updatequery)
lblmessage.Text = "Record updated successfully"
End Sub
Private Sub SearchButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles SearchButton.Click
If idTextbox.Text = "" Then
MsgBox("Please enter ID to search")
Exit Sub
End If
Dim cmd As New SqlCommand("Select * from class where id=@id", con)
cmd.Parameters.Add("@id", SqlDbType.Int).Value = idTextbox.Text
Dim ta As New SqlDataAdapter(cmd)
Dim table As New DataTable
ta.Fill(table)
nameTextbox.Text = ""
addressTextbox.Text = ""
rollnoTextbox.Text = ""
emailTextbox.Text = ""
If table.Rows.Count > 0 Then
nameTextbox.Text = table.Rows(0)(1).ToString()
addressTextbox.Text = table.Rows(0)(2).ToString()
rollnoTextbox.Text = table.Rows(0)(3).ToString()
emailTextbox.Text = table.Rows(0)(4).ToString()
lblmessage.Text = "Record found!"
Else
lblmessage.Text = "Sorry record not found"
End If
End Sub
Private Sub clearButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles clearButton.Click
clear()
End Sub
Private Sub exitButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles exitButton.Click
End
End Sub
End Class
82
VB.NET Arrays
An array is a linear data structure that is a collection of data elements of the same type
stored on a contiguous memory location. Each data item is called an element of the
array. It is a fixed size of sequentially arranged elements in computer memory with the
first element being at index 0 and the last element at index n - 1, where n represents
the total number of elements in the array.
In the above diagram, we store the Integer type data elements in an array starting at
index 0. It will continue to store data elements up to a defined number of elements.
83
Initialization of VB.NET Array
In VB.NET, we can initialize an array with New keyword at the time of declaration. For
example,
Furthermore, we can also initialize and declare an array using the following ways, as shown
below.
1. Dim intData() As Integer = {1, 2, 3, 4, 5}
2. Dim intData(5) As Integer
3. Dim array_name() As String = {"Peter", "John", "Brock", "James", "Maria"}
4. Dim misc() as Object = {"Hello friends", 16c, 12ui, "A"c}
5. Dim Emp(0 to 2) As String
6. Emp{0} = "Mathew"
7. Emp(1) = " Anthony"
8. Emp(2) = "Prince"
Let's create a program to add the elements of an array in VB.NET programming language.
1. Imports System
2. Module num_Array
3. Sub Main()
4. Dim i As Integer, Sum As Integer = 0
5. 'In VB.NET the size of an array is n+1
6. 'Declaration and Initialization of marks() array
7. Dim marks() As Integer = {58, 68, 95, 50, 23, 89}
8. Console.WriteLine(" Marks in 6 Subjects")
9. For i = 0 To marks.Length - 1
84
10. Console.WriteLine(" Marks {0}", marks(i))
11. Sum = Sum + marks(i)
12. Next
13. Console.WriteLine(" Grand total is {0}", Sum)
14.
15. Console.WriteLine(" Press any key to exit...")
16. Console.ReadKey()
17. End Sub
18. End Module
Input_array.vb
1. Imports System
2. Module Input_array
3. Sub Main()
4. 'Definition of array
5. Dim arr As Integer() = New Integer(5) {}
6. For i As Integer = 0 To 5
7. Console.WriteLine(" Enter the value for arr[{0}] : ", i)
8. arr(i) = Console.ReadLine() ' Accept the number in array
9. Next
10. Console.WriteLine(" The array elements are : ")
11. ' Definition of For loop
12. For j As Integer = 0 To 5
13.
14. Console.WriteLine("{0}", arr(j))
15. Next
16.
17. Console.WriteLine(" Press any key to exit...")
85
18. Console.ReadKey()
19. End Sub
20. End Module
86