IT 6th MAIN VB - Net Manual
IT 6th MAIN VB - Net Manual
Visual Basic, the name makes me feel that it is something special. In the History of Computing world no
other product sold more copies than Visual Basic did. Such is the importance of that language which clearly
states how widely it is used for developing applications. Visual Basic is very popular for it's friendly
working (graphical) environment. Visual Basic. NET is an extension of Visual Basic programming
language with many new features in it. The changes from VB to VB .NET are huge, ranging from the
change in syntax of the language to the types of projects we can create now and the way we design
applications. Visual Basic .NET was designed to take advantage of the .NET Framework base classes and
runtime environment. It comes with power packed features that simplify application development.
The biggest change from VB to VB .NET is, VB .NET is Object-Oriented now. VB .NET now supports
all the key OOP features like Inheritance, Polymorphism, Abstraction and Encapsulation. We can now
create classes and objects, derive classes from other classes and so on. The major advantage of OOP is
code reusability
The Command Button now is Button and the TextBox is TextBox instead of Text as in VB6
Many new controls have been added to the toolbar to make application development more efficient
VB .NET now adds Console Applications to it apart from Windows and Web Applications. Console
applications are console oriented applications that run in the DOS version
All the built-in VB functionality now is encapsulated in a Namespace (collection of different classes)
called System
New keywords are added and old one's are either removed or renamed
VB .NET is strongly typed which means that we need to declare all the variables by default before using
them
VB .NET now supports structured exception handling using Try...Catch...Finally syntax
The syntax for procedures is changed. Get and Let are replaced by Get and Set
Event handling procedures are now passed only two parameters
The way we handle data with databases is changed as well. VB .NET now uses ADO .NET, a new data
handling model to communicate with databases on local machines or on a network and also it makes
handling of data on the Internet easy. All the data in ADO .NET is represented in XML format and is
exchanged in the same format. Representing data in XML format allows us for sending large amounts of
data on the Internet and it also reduces network traffic when communicating with the database
VB .NET now supports Multithreading. A threaded application allows to do number of different things at
once, running different execution threads allowing to use system resources
Web Development is now an integral part of VB .NET making Web Forms and Web Services two major
types of applications
Problems with VB 6.0
In VB.NET all these shortcomings have been eliminated. we will discuss how VB.NET implements all
these features in our subsequent articles one by one. In fact VB gets the most extensive changes of any
existing language in the Visual Studio suite. Let us talk about the major features VB.NET has developed.
OOP with VB
OOP Basics
Visual Basic was Object-Based, Visual Basic .NET is Object-Oriented, which means that it's a true Object-
Oriented Programming Language. Visual Basic .NET supports all the key OOP features like Polymorphism,
Inheritance, Abstraction and Encapsulation. It's worth having a brief overview of OOP before starting OOP
with VB.
A major factor in the invention of Object-Oriented approach is to remove some of the flaws encountered
with the procedural approach. In OOP, data is treated as a critical element and does not allow it to flow
freely. It bounds data closely to the functions that operate on it and protects it from accidental modification
from outside functions. OOP allows decomposition of a problem into a number of entities called objects
and then builds data and functions around these objects. A major advantage of OOP is code reusability.
Concepts of OOP:
o Objects
o Classes
o Data Abstraction and Encapsulation
o Inheritance
o Polymorphism
Briefly on Concepts:
Objects
Objects are the basic run-time entities in an object-oriented system. Programming problem is analyzed in
terms of objects and nature of communication between them. When a program is executed, objects interact
with each other by sending messages. Different objects can also interact with each other without knowing
the details of their data or code.
Classes
A class is a collection of objects of similar type. Once a class is defined, any number of objects can be
created which belong to that class.
Abstraction refers to the act of representing essential features without including the background details
or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes.
Storing data and functions in a single unit (class) is encapsulation. Data cannot be accessible to the outside
world and only those functions which are stored in the class can access it.
Inheritance
Inheritance is the process by which objects can acquire the properties of objects of other class. In OOP,
inheritance provides reusability, like, adding additional features to an existing class without modifying it.
This is achieved by deriving a new class from the existing one. The new class will have combined features
of both the classes.
Polymorphism
Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors
in different instances. The behavior depends on the data types used in the operation. Polymorphism is
extensively used in implementing Inheritance.
Advantages of OOP
o OOP provides a clear modular structure for programs which makes it good for defining abstract
datatypes where implementation details are hidden and the unit has a clearly defined interface.
o OOP makes it easy to maintain and modify existing code as new objects can be created with small
differences to existing ones.
o OOP provides a good framework for code libraries where supplied software components can be
easily adapted and modified by the programmer. This is particularly useful for developing
graphical user interfaces.
OOP with VB
Visual Basic .NET is Object-Oriented. Everything we do in Visual Basic involves objects in some way or
other and everything is based on the Object class. Controls, Forms, Modules, etc are all types of classes.
Visual Basic .NET comes with thousands of built-in classes which are ready to be used. Let's take a closer
look at Object-Oriented Programming in Visual Basic. We will see how we can create classes, objects, how
to inherit one class from other, what is polymorphism, how to implement interfaces and so on. We will
work with Console Applications here as they are simple to code.
Classes are types and Objects are instances of the Class. Classes and Objects are very much related to each
other. Without objects you can't use a class. In Visual Basic we create a class with the Class statement and
end it with End Class. The Syntax for a Class looks as follows:
Public Class Test
----- Variables
-----Methods
-----Properties
-----Events
End Class
The above syntax created a class named Test. To create a object for this class we use the new keyword and
that looks like this: Dim obj as new Test(). The following code shows how to create a Class and access the
class with an Object. Open a Console Application and place the following code in it.
Module Module1
Imports System.Console
Sub Main()
Dim obj As New Test()
'creating a object obj for Test class
obj.disp()
'calling the disp method using obj
Read()
End Sub
End Module
Fields, Properties, Methods, and Events are members of the class. They can be declared as Public, Private,
Protected, Friend or Protected Friend.
Fields and Properties represent information that an object contains. Fields of a class are like variables and
they can be read or set directly. For example, if you have an object named House, you can store the
numbers of rooms in it in a field named Rooms. It looks like this:
Properties are retrieved and set like fields but are implemented using Property Get and Property Set
procedures which provide more control on how values are set or returned.
Methods represent the object’s built-in procedures. For example, a Class named Country may have
methods named Area and Population. You define methods by adding procedures, Sub routines or functions
to your class. For example, implementation of the Area and Population methods discussed above might
look like this
Constructors
A constructor is a special member function whose task is to initialize the objects of it's class. This is the
first method that is run when an instance of a type is created. A constructor is invoked whenever an object
of it's associated class is created. If a class contains a constructor, then an object created by that class will
be initialized automatically. We pass data to the constructor by enclosing it in the parentheses following the
class name when creating an object. Constructors can never return a value, and can be overridden to
provide custom intitialization functionality. In Visual Basic we create constructors by adding a Sub
procedure named New to a class. The following code demonstrates the use of constructors in Visual Basic.
Module Module1
Sub Main()
End Sub
End Module
Public Class Constructor
Public x As Integer
End Class
Destructors
A destructor, also know as finalizer, is the last method run by a class. Within a destructor we can place code
to clean up the object after it is used, which might include decrementing counters or releasing resources.
We use Finalize method in Visual Basic for this and the Finalize method is called automatically when
the .NET runtime determines that the object is no longer required. When working with destructors we need
to use the overrides keyword with Finalize method as we will override the Finalize method built into the
Object class. We normally use Finalize method to deallocate resources and inform other objects that the
current object is going to be destroyed. Because of the nondeterministic nature of garbage collection, it is
very hard to determine when a class's destructor will be called. The following code demonstrates the use of
Finalize method.
Module Module1
Sub Main()
Dim obj As New Destructor()
End Sub
End Module
End Class
When you run the above code, the word and object, obj of class, destructor is created and "Hello" is
displayed. When you close the DOS window, obj is destroyed.
Inheritance
A key feature of OOP is reusability. It's always time saving and useful if we can reuse something that
already exists rather than trying to create the same thing again and again. Reusing the class that is tested,
debugged and used many times can save us time and effort of developing and testing it again. Once a class
has been written and tested, it can be used by other programs to suit the program's requirement. This is
done by creating a new class from an existing class. The process of deriving a new class from an existing
class is called Inheritance. The old class is called the base class and the new class is called derived class.
The derived class inherits some or everything of the base class. In Visual Basic we use the Inherits keyword
to inherit one class from other. The general form of deriving a new class from an existing class looks as
follows:
Using Inheritance we can use the variables, methods, properties, etc, from the base class and add more
functionality to it in the derived class. The following code demonstrates the process of Inheritance in Visual
Basic.
Imports System.Console
Module Module1
Sub Main()
Dim ss As New Two()
WriteLine(ss.sum())
Read()
End Sub
End Module
End Class
Public Class Two
Inherits One
'derived class. class two inherited from class one
Public k As Integer = 100
End Class
Polymorphism
Polymorphism is one of the crucial features of OOP. It means "one name, multiple forms". It is also called
as Overloading which means the use of same thing for different purposes. Using Polymorphism we can
create as many functions we want with one function name but with different argument list. The function
performs different operations based on the argument list in the function call. The exact function to be
invoked will be determined by checking the type and number of arguments in the function.
Module Module1
Sub Main()
Dim two As New One()
WriteLine(two.add(10))
'calls the function with one argument
WriteLine(two.add(10, 20))
'calls the function with two arguments
WriteLine(two.add(10, 20, 30))
'calls the function with three arguments
Read()
End Sub
End Module
End Class
Interfaces
Interfaces allow us to create definitions for component interaction. They also provide another way of
implementing polymorphism. Through interfaces, we specify methods that a component must implement
without actually specifying how the method is implemented. We just specify the methods in an interface
and leave it to the class to implement those methods. Visual Basic .NET does not support multiple
inheritance directly but using interfaces we can achieve multiple inheritance. We use the Interface keyword
to create an interface and implements keyword to implement the interface. Once you create an interface you
need to implement all the methods specified in that interface. The following code demonstrates the use of
interface.
Imports System.Console
Module Module1
Sub Main()
Dim OneObj As New One()
Dim TwoObj As New Two()
'creating objects of class One and Two
OneObj.disp()
OneObj.multiply()
TwoObj.disp()
TwoObj.multiply()
'accessing the methods from classes as specified in the interface
End Sub
End Module
Public i As Double = 12
Public j As Double = 12.17
End Class
Public a As Double = 20
Public b As Double = 32.17
End Class
Abstract Classes
An abstract class is the one that is not used to create objects. An abstract class is designed to act as a base
class (to be inherited by other classes). Abstract class is a design concept in program development and
provides a base upon which other classes are built. Abstract classes are similar to interfaces. After declaring
an abstract class, it cannot be instantiated on it's own, it must be inherited. Like interfaces, abstract classes
can specify members that must be implemented in inheriting classes. Unlike interfaces, a class can inherit
only one abstract class. Abstract classes can only specify members that should be implemented by all
inheriting classes.
In Visual Basic .NET we create an abstract class by using the MustInherit keyword. An abstract class like
all other classes can implement any number of members. Members of an abstract class can either be
Overridable (all the inheriting classes can create their own implementation of the members) or they can
have a fixed implementation that will be common to all inheriting members. Abstract classes can also
specify abstract members. Like abstract classes, abstract members also provide no details regarding their
implementation. Only the member type, access level, required parameters and return type are specified. To
declare an abstract member we use the MustOverride keyword. Abstract members should be declared in
abstract classes.
When a class inherits from an abstract class, it must implement every abstract member defined by the
abstract class. Implementation is possible by overriding the member specified in the abstract class. The
following code demonstrates the declaration and implementation of an abstract class.
Module Module1
End Class
Sub Main()
Dim abs As New AbstractOne()
'creating an instance of AbstractOne
WriteLine("Sum is" & " " & abs.Add())
WriteLine("Multiplication is" & " " & abs.Mul())
'displaying output
Read()
End Sub
End Module
The output of above code is the image below.
VB Language
Visual Basic, the name makes me feel that it is something special. In the History of Computing world no
other product sold more copies than Visual Basic did. Such is the importance of that language which clearly
states how widely it is used for developing applications. Visual Basic is very popular for it's friendly
working (graphical) environment. Visual Basic. NET is an extension of Visual Basic programming
language with many new features in it. The changes from VB to VB .NET are huge, ranging from the
change in syntax of the language to the types of projects we can create now and the way we design
applications. Visual Basic .NET was designed to take advantage of the .NET Framework base classes and
runtime environment. It comes with power packed features that simplify application development.
The biggest change from VB to VB .NET is, VB .NET is Object-Oriented now. VB .NET now supports
all the key OOP features like Inheritance, Polymorphism, Abstraction and Encapsulation. We can now
create classes and objects, derive classes from other classes and so on. The major advantage of OOP is
code reusability
The Command Button now is Button and the TextBox is TextBox instead of Text as in VB6
Many new controls have been added to the toolbar to make application development more efficient
VB .NET now adds Console Applications to it apart from Windows and Web Applications. Console
applications are console oriented applications that run in the DOS version
All the built-in VB functionality now is encapsulated in a Namespace (collection of different classes)
called System
New keywords are added and old one's are either removed or renamed
VB .NET is strongly typed which means that we need to declare all the variables by default before using
them
VB .NET now supports structured exception handling using Try...Catch...Finally syntax
The syntax for procedures is changed. Get and Let are replaced by Get and Set
Event handling procedures are now passed only two parameters
The way we handle data with databases is changed as well. VB .NET now uses ADO .NET, a new data
handling model to communicate with databases on local machines or on a network and also it makes
handling of data on the Internet easy. All the data in ADO .NET is represented in XML format and is
exchanged in the same format. Representing data in XML format allows us for sending large amounts of
data on the Internet and it also reduces network traffic when communicating with the database
VB .NET now supports Multithreading. A threaded application allows to do number of different things at
once, running different execution threads allowing to use system resources
Web Development is now an integral part of VB .NET making Web Forms and Web Services two major
types of applications
Namespaces
A namespace is a collection of different classes. All VB applications are developed using classes from
the .NET System namespace. The namespace with all the built-in VB functionality is the System
namespace. All other namespaces are based on this System namespace.
System: Includes essential classes and base classes for commonly used data types, events, exceptions and
so on
System.Collections: Includes classes and interfaces that define various collection of objects such as list,
queues,
hash tables, arrays, etc
System.Data: Includes classes which lets us handle data from data sources
System.Data.OleDb: Includes classes that support the OLEDB .NET provider
System.Data.SqlClient: Includes classes that support the SQL Server .NET provider
System.Diagnostics: Includes classes that allow to debug our application and to step through our code
System.Drawing: Provides access to drawing methods
System.Globalization: Includes classes that specify culture-related information
System.IO: Includes classes for data access with Files
System.Net: Provides interface to protocols used on the internet
System.Reflection: Includes classes and interfaces that return information about types, methods and fields
System.Security: Includes classes to support the structure of common language runtime security system
System.Threading: Includes classes and interfaces to support multithreaded applications
System.Web: Includes classes and interfaces that support browser-server communication
System.Web.Services: Includes classes that let us build and use Web Services
System.Windows.Forms: Includes classes for creating Windows based forms
System.XML: Includes classes for XML support
Console Applications
Console Applications are command-line oriented applications that allow us to read characters from the
console, write characters to the console and are executed in the DOS version. Console Applications are
written in code and are supported by the System.Console namespace.
Create a folder in C: drive with any name (say, examples) and make sure the console applications which
you open are saved there. That's for your convenience. The default location where all the .NET applications
are saved is C:\Documents and Settings\Administrator\My Documents\Visual Studio Projects. The new
project dialogue looks like the image below.
The following code is example of a console application:
Module Module1
Sub Main()
System.Console.Write("Welcome to Console Applications")
End Sub
End Module
You run the code by selecting Debug->Start from the main menu or by pressing F5 on the keyboard. The
result "Welcome to Console Applications" displayed on a DOS window. Alternatively, you can run the
program using the VB compiler (vbc). To do that, go to the Visual Studio. NET command prompt selecting
from
Start->Programs->Visual Studio.NET->Visual Studio.NET Tools->Visual Studio.NET Command Prompt
and type:
c:\examples>vbc example1.vb.
The result, "Welcome to Console Applications" is displayed on a DOS window as shown in the image
below.
Breaking the Code to understand it
Note the first line, we're creating a Visual Basic Module and Modules are designed to hold code. All the
code which we write should be within the Module.
Next line starts with Sub Main(), the entry point of the program.
The third line indicates that we are using the Write method of the System.Console class to write to the
console.
Comments in VB.NET begin with a single quote (') character and the statements following that are ignored
by the compiler. Comments are generally used to specify what is going on in the program and also gives an
idea about the flow of the program. The general form looks like this:
Dim I as Integer
'declaring an integer
Code
The Data types available in VB .NET, their size, type, description are summarized in the table below.
Access Specifiers
Access specifiers let's us specify how a variable, method or a class can be used. The following are the most
commonly used one's:
Public: Gives variable public access which means that there is no restriction on their accessibility
Private: Gives variable private access which means that they are accessible only within their declaration
content
Protected: Protected access gives a variable accessibility within their own class or a class derived from that
class
Friend: Gives variable friend access which means that they are accessible within the program that contains
their declaration
Protected Friend: Gives a variable both protected and friend access
Static: Makes a variable static which means that the variable will hold the value even the procedure in
which they are declared ends
Shared: Declares a variable that can be shared across many instances and which is not associated with a
specific instance of a class or structure
ReadOnly: Makes a variable only to be read and cannot be written
Variables
Variables are used to store data. A variable has a name to which we refer and the data type, the type of data
the variable holds. VB .NET now needs variables to be declared before using them. Variables are declared
with the Dim keyword. Dim stands for Dimension.
Example
Imports System.Console
Module Module1
Sub Main()
Dim a,b,c as Integer
'declaring three variables of type integer
a=10
b=20
c=a+b
Write("Sum of a and b is" & c)
End Sub
End Module
Imports Statement
The Imports statement is used to import namespaces. Using this statement prevents you to list the entire
namespace when you refer to them.
Example of Imports Statement
The following code imports the namespace System.Console and uses the methods of that
namespace preventing us to refer to it every time we need a method of this namespace.
Imports System.Console
Module Module1
Sub Main()
Write("Imports Statement")
WriteLine("Using Import")
End Sub
End Module
The above two methods without an imports statement would look like this: System.Console.Write("Imports
Statement") and System.Console.WriteLine("Using Import")
With Statement
With statemnt is used to execute statements using a particular object. The syntax looks like this:
With object
[statements]
End With
Sample Code
The following code sets text and width for a button using the With Statement.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load
With Button1
.Text = "With Statement"
.Width = 150
End With
End Sub
Scope
The scope of an element in code is all the code that can refer to it without qualifying it's name. Stated other
way, an element's scope is it's accessibility in code. Scope is normally used when writing large programs as
large programs divide code into different classes, modules, etc. Also, scope prevents the chance of code
referring to the wrong item. The different kinds of scope available in VB .NET are as follows:
Block Scope: The element declared is available only within the code block in which it is declared.
Procedure Scope: The element declared is available only within the procedure in which it is declared.
Module Scope: The element is available to all code within the module and class in which it is declared.
Namespace Scope: The element declared is available to all code in the namespace.
Methods
A Method is a procedure built into the class. They are a series of statements that are executed when called.
Methods allow us to handle code in a simple and organized fashion. There are two types of methods in
VB .NET: those that return a value (Functions) and those that do not return a value (Sub Procedures).
Both of them are discussed below.
Sub Procedures
Sub procedures are methods which do not return a value. Each time when the Sub procedure is called the
statements within it are executed until the matching End Sub is encountered. Sub Main(), the starting point
of the program itself is a sub procedure. When the application starts execution, control is transferred to
Main Sub procedure automatically which is called by default.
Module Module1
Sub Main()
'sub procedure Main() is called by default
Display()
'sub procedure display() which we are creating
End Sub
Sub Display()
System.Console.WriteLine("Using Sub Procedures")
'executing sub procedure Display()
End Sub
End Module
The image below displays output from above code.
Functions
Function is a method which returns a value. Functions are used to evaluate data, make calculations or to
transform data. Declaring a Function is similar to declaring a Sub procedure. Functions are declared with
the Function keyword. The following code is an example on Functions:
Imports System.Console
Module Module1
Sub Main()
Write("Sum is" & " " & Add())
'calling the function
End Sub
End Module
The image below displays output from above code.
Calling Methods
A method is not executed until it is called. A method is called by referencing it's name along with any
required parameters. For example, the above code called the Add method in Sub main like this:
Write("Sum is" & " " & Add()).
Method Variables
Variables declared within methods are called method variables. They have method scope which means that
once the method is executed they are destroyed and their memory is reclaimed. For example, from the
above code (Functions) the Add method declared two integer variables i, j. Those two variables are
accessible only within the method and not from outside the method.
Parameters
A parameter is an argument that is passed to the method by the method that calls it. Parameters are enclosed
in parentheses after the method name in the method declaration. You must specify types for these
parameters. The general form of a method with parameters looks like this:
Conditional Statements
If....Else statement
If conditional expression is one of the most useful control structures which allows us to execute a
expression if a condition is true and execute a different expression if it is False. The syntax looks like this:
If condition Then
[statements]
Else If condition Then
[statements]
-
-
Else
[statements]
End If
If the condition is true, the statements following the Then keyword will be executed, else, the statements
following the ElseIf will be checked and if true, will be executed, else, the statements in the else part will
be executed.
Example
Imports System.Console
Module Module1
Sub Main()
Dim i As Integer
WriteLine("Enter an integer, 1 or 2 or 3")
i = Val(ReadLine())
'ReadLine() method is used to read from console
If i = 1 Then
WriteLine("One")
ElseIf i = 2 Then
WriteLine("Two")
ElseIf i = 3 Then
WriteLine("Three")
Else
WriteLine("Number not 1,2,3")
End If
End Sub
End Module
The image below displays output from above code.
Select....Case Statement
The Select Case statement executes one of several groups of statements depending on the value of an
expression. If your code has the capability to handle different values of a particular variable then you can
use a Select Case statement. You use Select Case to test an expression, determine which of the given cases
it matches and execute the code in that matched case.
Example
Imports System.Console
Module Module1
Sub Main()
Dim keyIn As Integer
WriteLine("Enter a number between 1 and 4")
keyIn = Val(ReadLine())
End Sub
End Module
For Loop
The For loop is the most popular loop. For loops enable us to execute a series of expressions multiple
numbers of times. The For loop in VB .NET needs a loop index which counts the number of loop iterations
as the loop executes. The syntax for the For loop looks like this:
The index variable is set to start automatically when the loop starts. Each time in the loop, index is
incremented by step and when index equals end, the loop ends.
Module Module1
Sub Main()
Dim d As Integer
For d = 0 To 2
System.Console.WriteLine("In the For Loop")
Next d
End Sub
End Module
While loop keeps executing until the condition against which it tests remain true. The syntax of while loop
looks like this:
While condition
[statements]
End While
Module Module1
Sub Main()
Dim d, e As Integer
d=0
e=6
While e > 4
e -= 1
d += 1
End While
System.Console.WriteLine("The Loop ran " & e & "times")
End Sub
End Module
Do Loop
The Do loop can be used to execute a fixed block of statements indefinite number of times. The Do loop
keeps executing it's statements while or until the condition is true. Two keywords, while and until can be
used with the do loop. The Do loop also supports an Exit Do statement which makes the loop to exit at any
moment. The syntax of Do loop looks like this:
Do[{while | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
Example on Do loop
Module Module1
Sub Main()
Dim str As String
Do Until str = "Cool"
System.Console.WriteLine("What to do?")
str = System.Console.ReadLine()
Loop
End Sub
End Module
Attributes are those that lets us specify information about the items we are using in VB .NET. Attributes
are enclosed in angle brackets(< >) and are used when VB .NET needs to know more beyond the standard
syntax.
The files and their extensions which are created as part of the Windows Application Project and their
meaning are summarized below:
Language Terminology
Operators
Visual Basic comes with many built-in operators that allow us to manipulate data. An operator performs a
function on one or more operands. For example, we add two variables with the "+" addition operator and
store the result in a third variable with the "=" assignment operator like this: int x + int y = int z. The two
variables (x ,y) are called operands. There are different types of operators in Visual Basic and they are
described below in the order of their precedence.
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations that involve calculation of
numeric values. The table below summarizes them:
Operator Use
^ Exponentiation
Negation (used to reverse the sign of the given value, exp
-
-intValue)
* Multiplication
/ Division
\ Integer Division
Mod Modulus Arithmetic
+ Addition
- Subtraction
Concatenation Operators
Concatenation operators join multiple strings into a single string. There are two
concatenation operators, + and & as summarized below:
Operator Use
+ String Concatenation
& String Concatenation
Comparison Operators
A comparison operator compares operands and returns a logical value based on whether
the comparison is true or not. The table below summarizes them:
Operator Use
= Equality
<> Inequality
< Less than
> Greater than
>= Greater than or equal to
<= Less than or equal to
Operator Use
Not Negation
And Conjunction
AndAlso Conjunction
Or Disjunction
OrElse Disjunction
Xor Disjunction
Arithmetic Operators
Imports System.Console
Module Module1
Sub Main()
Dim x, y, z As Integer
x = 30
y = 20
z=x+y
WriteLine("Addition" & " = " & z)
z=x-y
WriteLine("Subtraction" & " = " & z)
z=x*y
WriteLine("Multiplication" & " = " & z)
z=x/y
WriteLine("Division" & " = " & z)
Read()
End Sub
End Module
Imports System.Console
Module Module1
Sub Main()
Dim str1, str2, str3, str4 As String
str1 = "Concatenation"
str2 = "Operators"
str3 = str1 + str2
WriteLine(str3)
str4 = str1 & str2
WriteLine(str4)
Read()
End Sub
End Module
Imports System.Console
Module Module1
Sub Main()
Dim x, y As Integer
WriteLine("enter values for x and y ")
x = Val(ReadLine())
y = Val(ReadLine())
If x = y Then
WriteLine("x is equal to y")
ElseIf x < y Then
WriteLine("x is less than y")
ElseIf x > y Then
WriteLine("x is greater than y")
End If
Read()
End Sub
End Module
The image below displays output from above code.
Imports System.Console
Module Module1
Sub Main()
Dim x As Boolean
x = Not 45 > 26
WriteLine("x not is false")
' x equals false
x = Not 26 > 87
' x equals True
WriteLine("x not is true")
Read()
End Sub
End Module
The image below displays output from above code.
Enumeration
Enumeration is a related set of constants. They are used when working with many constants of the same
type. It's declared with the Enum keyword.
Example
Imports System.Console
Module Module1
Enum Seasons
Summer = 1
Winter = 2
Spring = 3
Autumn = 4
End Enum
Sub Main()
Write("Summer is the" & Seasons.Summer & "season")
End Sub
End Module
Output of above code is the image below. To use a constant from the enumeration it should be referred like
this, Seasons.Winter and so on.
Constants
When we have certain values that we frequently use while programming, we should use Constants. A value
declared as constant is of fixed value that cannot be changed once set. Constants should be declared as
Public if we want it to be accessed by all parts of the application. In Visual Basic .NET we use the Const
keyword to declare a constant. The following line of code declares a constant: Public Const Pi as
Double=3.14159265
Exception Handling
Exceptions are runtime errors that occur when a program is running and causes the program to abort
without execution. Such kind of situations can be handled using Exception Handling. By placing specific
lines of code in the application we can handle most of the errors that we may encounter and we can enable
the application to continue running. VB .NET supports two ways to handle exceptions, Unstructured
exception Handling using the on error goto statement and Structured exception handling using
Try....Catch.....Finally
Let's look at the new kind of exception handling introduced in VB .NET which is the Structured Exception
Handling. VB .NET uses Try....Catch....Finally block type exception handling. The syntax looks like this:
Module Module1
Sub Main()
Try
-
-
Catch e as Exception
-
-
Finally
End Try
End Sub
End Module
Example
Imports System.Console
Module Module1
Sub Main()
Dim a = 0, b = 1, c As Integer
Try
c=b/a
'the above line throws an exception
WriteLine("C is " & c)
Catch e As Exception
WriteLine(e)
'catching the exception
End Try
End Sub
End Module
The output of the above code displays a message stating the exception. The reason for the exception is
because any number divided by zero is infinity. When working with Structured exception handling you can
have multiple Catch blocks to handle different types of exceptions differently. The code in the Finally block
is optional. If there is a Finally block in the code then that code is executed last.
Arrays
Arrays are programming constructs that store data and allow us to access them by numeric index or
subscript. Arrays helps us create shorter and simpler code in many situations. Arrays in Visual Basic .NET
inherit from the Array class in the System namespace. All arrays in VB as zero based, meaning, the index of
the first element is zero and they are numbered sequentially. You must specify the number of array elements
by indicating the upper bound of the array. The upper bound is the numder that specifies the index of the
last element of the array. Arrays are declared using Dim, ReDim, Static, Private, Public and Protected
keywords. An array can have one dimension (liinear arrays) or more than one (multidimensional arrays).
The dimensionality of an array refers to the number of subscripts used to identify an individual element. In
Visual Basic we can specify up to 32 dimensions. Arrays do not have fixed size in Visual Basic.
Imports System.Console
Module Module1
Sub Main()
Dim sport(5) As String
'declaring an array
sport(0) = "Soccer"
sport(1) = "Cricket"
sport(2) = "Rugby"
sport(3) = "Aussie Rules"
sport(4) = "BasketBall"
sport(5) = "Hockey"
'storing values in the array
WriteLine("Name of the Sport in the third location" & " " & sport(2))
'displaying value from array
End Sub
End Module
The above code declared a sport array of type string like this: Dim sport(5) as String. This sport array has
6 elements starting from sport(0) to sport(5). The first element of an array is always referred by zero index.
The image below displays output from above code.
You can also declare an array without specifying the number of elements on one line, you must provide
values for each element when initializing the array. The following lines demonstrate that:
Dim Test() as Integer
'declaring a Test array
Test=New Integer(){1,3,5,7,9,}
Reinitializing Arrays
We can change the size of an array after creating them. The ReDim statement assigns a completely new
array object to the specified array variable. You use ReDim statement to change the number of elements in
an array. The following lines of code demonstrate that. This code reinitializes the Test array declared
above.
When using the Redim statement all the data contained in the array is lost. If you want to preserve existing
data when reinitializing an array then you should use the Preserve keyword which looks like this:
Multidimensional Arrays
All arrays which were mentioned above are one dimensional or linear arrays. There are two kinds of
multidimensional arrays supported by the .NET framework: Rectangular arrays and Jagged arrays.
Rectangular arrays
Rectangular arrays are arrays in which each member of each dimension is extended in each other
dimension by the same length. We declare a rectangular array by specifying additional dimensions at
declaration. The following lines of code demonstrate the declaration of a multidimensional array.
Visual Studio .NET IDE (Integrated Development Environment) is the Development Environment for
all .NET based applications which comes with rich features. VS .NET IDE provides many options and is
packed with many features that simplify application development by handling the complexities. Visual
Studio .NET IDE is an enhancement to all previous IDE’s by Microsoft.
Important Features
Visual Studio .NET IDE provides a single environment for developing all types of .NET applications.
Application’s range from single windows applications to complex n-tier applications and rich web
applications.
You can choose the programming language of your choice to develop applications based on your expertise
in that language. You can also incorporate multiple programming languages in one .NET solution and edit
that with the IDE.
IDE is Customizable
You can customize the IDE based on your preferences. The My Profile settings allow you to do this. With
these settings you can set the IDE screen the way you want, the way the keyboard behaves and you can also
filter the help files based on the language of your choice.
Built-in Browser
The IDE comes with a built-in browser that helps you browse the Internet without launching another
application. You can look for additional resources, online help files, source codes and much more with this
built-in browser feature.
The New Project dialogue box like the one in the image below is used to create a new project specifying it's
type allowing us to name the project and also specify it's location on the disk where it is saved. The default
location on the hard disk where all the projects are saved is
C:\DocumentsandSettings\Administrator\MyDocuments\VisualStudioProjects.
Following are different templates under Project Types and their use.
Windows Application: This template allows to create standard windows based applications.
Class Library: Class libraries are those that provide functionality similar to Active X and DLL by creating
classes that access other applications.
Windows Control Library: This allows to create our own windows controls. Also called as User Controls,
where you group some controls, add it to the toolbox and make it available to other projects.
ASP .NET Web Application: This allows to create web-based applications using IIS. We can create web
pages, rich web applications and web services.
Web Control Library: Allows to create User-defined controls for the Web. Similar to user defined
windows controls but these are used for Web.
Console Application: A new kind of application in Visual Studio .NET. They are command line based
applications.
Windows Service: These run continuously regardless of the user interaction. They are designed for special
purpose and once written, will keep running and come to an end only when the system is shut down.
Other: This template is to develop other kinds of applications like enterprise applications, database
applications etc.
Solution Explorer Window
The Solution Explorer window gives an overview of the solution we are working with and lists all the files
in the project. An image of the Solution Explorer window is shown below.
The Server Explorer window is a great tool that provides "drag and drop" feature and helps us work with
databases in an easy graphical environment. For example, if we drag and drop a database table onto a form,
VB .NET automatically creates connection and command objects that are needed to access that table. The
image below displays Server Explorer window.
Intelligence
Intelligence is what that is responsible for the boxes that open as we type the code. IntelliSense provides a
list of options that make language references easily accessible and helps us to find the information we need.
They also complete the typing for us. The image below displays that.
Code Designers like the image below allows us to edit and write code. This is the window that opens when
we double-click on a form or any control. This is the place where we write all the code for the application.
Notice the two drop-down list boxes at the top of the code window in the image below. The left box allows
us to select the object's code we are working with and the right box allows us to select the part of code that
we want to work. Also notice the "+" and "-" boxes in the code designer. You can use those boxes to display
code Visual Basic .NET already created, like, Windows Forms Designer generated code, etc.
Properties Window
The properties window allows us to set properties for various objects at design time. For example, if you
want to change the font, font size, backcolor, name, text that appears on a button, textbox etc, you can do
that in this window. Below is the image of properties window. You can view the properties window by
selecting
View->Properties Window from the main menu or by pressing F4 on the keyboard.
Dynamic Help Window
The dynamic help window displays help which looks up for things automatically. For example, if you want
to get help with a form, select the form and select Help->Dynamic Help from the main menu. Doing that
displays all the information relating to forms. The image below displays that. You can get help relating to
anything with this feature. Say, if you want to know more about the form, select the form and select
Dynamic Help from the Help menu. Doing that displays information about the form as shown in the image
below..
Command Window
The command window in the image below is a useful window. Using this window we can add new item to
the project, add new project and so on. You can view the command window by selecting
View->Other Windows->Command Window from the main menu. The command window in the image
displays all possible commands with File.
The class view window like the image below is the window that presents solutions and projects in terms of
the classes they contain and the members of these classes. Using the class view window also helps us to
find a member of a class that we want to work with. As you can notice from the image, the class view
window displayed all the methods and events for the controls which were available on the form.
Output Window
The output window as you can see in the image below displays the results of building and running
applications.
The object explorer window allows us to view all the members of an object at once. It lists all the objects in
our code and gives us access to them. The image below displays an object explorer window. You can view
the object explorer window by selecting View->Other Windows-> Object Browser from the main menu.
Toolbox Window
The toolbox window is the window that gives us access to all controls, components, etc. As you can see
from the image below, the toolbox uses tabs to divide it's contents into categories (Data, Components,
Windows Forms and General). The Data tab displays tools for creating datasets and making data
connections, the Windows Forms tab displays tools for adding controls to forms, the General tab is left
empty by default, the Clipboard Ring tab displays recent items stored in the clipboard and allows us to
select from them.
Windows Forms
In Visual Basic its these Forms with which we work. They are the base on which we build, develop all our
user interface and they come with a rich set of classes. Forms allow us to work visually with controls and
other items from the toolbox. In VB .NET forms are based on the System.Windows.Forms namespace and
the form class is System.Windows.Forms.Form. The form class is based on the Control class which allows
it to share many properties and methods with other controls.
When we open a new project in Visual Basic the dialogue box that appears first is the one which looks like
the image below. Since we are working with Windows Applications (Forms) you need to select
WindowsApplication and click OK.
Once you click OK a new Form opens with the title, Form1, towards the top-left side of the form and
maximize, minimize and close buttons towards the top right of the form. The whole form is surrounded
with a border. The main area of the form in which we work is called the Client Area. It's in this client area
we design the user interface leaving all the code to the code behind file. Forms also support events which
let's the form know that something happened with the form, for example, when we double-click on the
form, the Form load event occurs. VB .NET also supports forms to be inherited.
End Sub
End Sub
#End Region
End Sub
End Class
Below are the properties of a Windows Form. Properties displayed below are categorized as seen in the
properties window.
Gets/Sets the cursor to be displayed when the user moves the mouse
Cursor
over the form
AllowDrop Indicates if the form can accept data that the user drags and drops into it
Indicates if the form adjusts its size to fit the height of the font used on the
AutoScale
form and scales its controls
AutoScrollMinSize The minimum logical size for the auto scroll region
MiscProperties Description
Gets/Sets the button on the form that is pressed when the user uses the enter
AcceptButton
key
CancelButton Indicates the button control that is pressed when the user presses the ESC key
KeyPreview Determines whether keyboard controls on the form are registered with the form
Window Style
Description
Properties
HelpButton Determines whether a form has a help button on the caption bar
SizeGripStyle Determines when the size grip will be displayed for the form
TransparencyKey A color which will appear transparent when painted on the form
Well, let's now start working with Forms. When you open a new form you can have a look at the default
properties of the form by selecting View->Properties Window or by pressing F4 on the keyboard. The
properties window opens with default properties set to form by the software.
Appearance
Appearance section of the properties window allow us to make changes to the appearance of the form. With
the help of appearance properties we can have a background color, background image for the entire form,
set the border style for the form from a predefined list, change the cursor, set the font for the text on the
form and so on.
Behavior
Notable Behavior property is the enabled property which lets us enable/disable the form by setting the
property to True/False.
Layout
Layout properties are all about the structure of the form. With these properties we can set the location of the
form, maximum size of the form, minimum size of the form, exact size of the form with the size property
when designing. Note the property start position, this property lets you specify the location of the form
where it should appear when you run the application which you can select from a predefined list.
Window Style
The notable property under this is the ControlBox property which by default it is set to True. Setting the
property to False makes the minimize, maximize and cancel buttons on the top right side of the form
invisible.
Form Event
The default event of a form is the load event which looks like this in code:
End Sub
You can write code in the load event of the form just like you write for all other controls.
An Example:
You can run the Form by selecting Debug->Start from the main menu or by pressing F5 on the keyboard.
When you run a blank form with no controls on it, nothing is displayed. It looks like the image below.
Now, add a TextBox and a Button to the form from the toolbox. The toolbox can be selected from
View->ToolBox on the main menu or by holding Ctrl+Alt+X on the keyboard. Once adding the TextBox
and Button is done, run the form. The output window displays a TextBox and a Button. When you click the
Button nothing happens. We need to write an event for the Button stating something should happen when
you click it. To do that get back to design view and double-click on the Button. Doing that opens an event
handler for the Button where you specify what should happen when you click the button. That looks like
this in code.
Place the code TextBox1.Text="Welcome to Forms" in the Click event of the Button and run the
application. When you click the Button the output "Welcome to Forms" is displayed in the TextBox.
Alternatively, you can also use the MsgBox or MessageBox functions to display text when you click on the
Button. To do that place a Button on the form and double-click on that to open it's event. Write this line of
code, MsgBox("Welcome to Forms") or MessageBox.Show("Welcome to Forms").
or
When you run the form and click the Button, a small message box displays, "Welcome to Forms". The
image below displays that.
Adding a New Form to the Project
You can add a new form to the project with which you are working. To do that, select File->Add New Item
from the main menu which displays a window asking you what to add to the project. Select Windows Form
from the window and click Open to add a new form to the project. Alternatively, you can add a new form
with the Solution Explorer. To add a new form with the Solution Explorer, right-click on the project name
in Solution Explorer and Select Add->Add Windows Form. Once you finish adding a new form, if you
want the form which you added to be displayed when you run the application you need to make some
changes. You need to set the new form as Startup Object. To do that, right-click on the project name in
Solution Explorer window and select Properties which displays the Property Pages window. On this
window click the drop-down box which is labeled as Startup Object. Doing that displays all the forms
available in the project. It looks like the image below.
Select the form which you want to be displayed when you run the application and click Apply. Now, when
you run the application, the form you assigned as Startup object will be displayed.
Let's see how we can work with more than one form/open a new form. Say, for example, we want to open a
new form (Form2) when a button in the current form (Form1) is clicked. To do that, open a new project by
selecting File->New->Project->Visual Basic->WindowsApplication. This adds a form (Form1) to the
application. Add a new form (Form2) by selecting File->Add New Item->Windows Form. Also, drag a
button (Button1) onto Form1. We want to open Form2 when the button in Form1 is clicked. Unlike earlier
versions of Visual Basic, VB .NET requires us to refer to Form2 in Form1 in order to open it i.e creating an
object of Form2 in Form1. The code for that looks like this:
As we know, Inheritance allows us to derive one class from another. VB. NET allows us to inherit one form
from another. Let's see how we can inherit a new form from an existing form. Say, we have a form named
Form1 with some controls on it and we want to inherit a new form from that form. To derive a new form
from the existing one select Project->Add Inherited Form from the main menu. Doing that opens the Add
New Item window. Double-click on the Inherited Form Icon in the templates box to open the Inheritance
Picker. Inheritance Picker window looks like the image below.
Select Form1 in the picker and click OK. Clicking OK adds a new form, Form2, which is derived from
Form1. Everything on Form2 including the title is copied from Form1. The only difference between form1
and form2 is, the controls on Form2 come with a special icon at the upper left corner which indicates that
the form is inherited and the controls are locked. The image below displays a Inherited Form.
Inheriting a Form from Other Project
You can also inherit a form from other project. To inherit a form from other project, navigate to the project
containing the form you want using the browse button in the Inheritance Picker dialog, click the name of
the DLL file containing the form and click Open. This returns to the inheritance Picker dialog box where
the selected project is now listed. Choose the appropriate form and click OK. A new inherited form is added
to your project.
Owned Forms
Visual Basic also allows us to create owned forms. An owned form is tied to the form that owns it. If you
minimize the owner form, the owned form will also be minimized, if you close the owner form, the owned
form will be closed and so on. Owned Forms are added to a form with the AddOwnedForm method and
removed with the RemoveOwnedForm method. The following code demonstrates the creation of owned
forms. Drag a Button from the toolbox onto the form (form1). When you click the button, Form1 will make
an object of the Form class into an owned form and displays it. The code for that looks like this:
InputBox function gets a string of text entered by the user. They are similar to the JavaScript prompt
windows that ask us to enter some text and performs some action after the OK button is clicked. In Visual
Basic Input boxes let you display a prompt, read the text entered by the user and returns a string result. The
following code demonstrates InputBox function. Drag a Button and TextBox control from the toolbox onto
the form. When you click the Button, InputBox asks to enter some text and after you click OK it displays
the text you entered in the TextBox. The image below displays output.
We can handle mouse events such as mouse pointer movements in Forms. The mouse events supported by
VB .NET are as follows:
MouseDown: This event happens when the mouse pointer is over the form/control and is pressed
MouseEnter: This event happens when the mouse pointer enters the form/control
MouseUp: This event happens when the mouse pointer is over the form/control and the mouse button is
released
MouseLeave: This event happens when the mouse pointer leaves the form/control
MouseMove: This event happens when the mouse pointer is moved over the form/control
MouseWheel: This event happens when the mouse wheel moves while the form/control has focus
MouseHover: This event happens when the mouse pointer hovers over the form/control
The properties of the MouseEventArgs objects that can be passed to the mouse event handler are as
follows:
We will work with an example to check the mouse events in a form. We will be working with MouseDown,
MouseEnter and MouseLeave events in this example. Drag three TextBoxes (TextBox1, TextBox2,
TextBox3) onto the form. The idea here is to display the results of these events in the TextBoxes.
Code
End Class
The image below displays the output.
Beep Function
The Beep Function in VB.NET can be used to make the computer emit a beep. To see how this works, drag
a Button onto the form and place the following code in it's click event:
When you run the code and click the button your computer emits a beep.
Controls
A control is an object that can be drawn on to the Form to enable or enhance user interaction with the
application. Examples of these controls, TextBoxes, Buttons, Labels, Radio Buttons, etc. All these
Windows Controls are based on the Control class, the base class for all controls. Visual Basic allows us to
work with controls in two ways: at design time and at runtime. Working with controls at design time means,
controls are visible to us and we can work with them by dragging and dropping them from the Toolbox and
setting their properties in the properties window. Working at runtime means, controls are not visible while
designing, are created and assigned properties in code and are visible only when the application
is executed. There are many new controls added in Visual Basic .NET and we will be working with some of
the most popular controls in this section. You can select the controls from the menu towards the left-hand
side of this page.
Notable properties of most of these Windows Controls which are based on the Control class itself are
summarized in the table below. You can always find the properties of the control with which you are
working by pressing F4 on the keyboard or by selecting View->Properties Window from the main menu.
Button Control
One of the most popular control in Visual Basic is the Button Control (previously Command Control). They
are the controls which we click and release to perform some action. Buttons are used mostly for handling
events in code, say, for sending data entered in the form to the database and so on. The default event of the
Button is the Click event and the Button class is based on the ButtonBase class which is based on the
Control class.
Button Event
The default event of the Button is the Click event. When a Button is clicked it responds with the Click
Event. The Click event of Button looks like this in code:
Well, it's time to work with Buttons. Drag a Button from the toolbox onto the Form. The default text on the
Button is Button1. Click on Button1 and select it's properties by pressing F4 on the keyboard or by
selecting
View->Properties Window from the main menu. That displays the Properties for Button1.
Appearance
Appearance section of the properties window allows us to make changes to the appearance of the Button.
With the help of BackColor and Background Image properties we can set a background color and a
background image to the button. We set the font color and font style for the text that appears on button with
ForeColor and the Font property. We change the appearance style of the button with the FlatStyle property.
We can change the text that appears on button with the Text property and with the TextAlign property we
can set where on the button the text should appear from a predefined set of options.
Behavior
Notable Behavior properties of the Button are the Enabled and Visible properties. The Enabled property is
set to True by default which makes the button enabled and setting it's property to False makes the button
Disabled. With the Visible property we can make the Button Visible or Invisible. The default value is set to
True and to make the button Invisible set it's property to False.
Layout
Layout properties are about the look of the Button. Note the Dock property here. A control can be docked to
one edge of its parent container or can be docked to all edges and fill the parent container. The default value
is set to none. If you want to dock the control towards the left, right, top, bottom and center you can do that
by selecting from the button like image this property displays. With the Location property you can change
the location of the button. With the Size property you can set the size of the button. Apart from the Dock
property you can set it's size and location by moving and stretching the Button on the form itself.
Below is the image of a Button.
TextBox Control
Windows users should be familiar with textboxes. This control looks like a box and accepts input from the
user. The TextBox is based on the TextBoxBase class which is based on the Control class. TextBoxes are
used to accept input from the user or used to display text. By default we can enter up to 2048 characters in a
TextBox but if the Multiline property is set to True we can enter up to 32KB of text. The image below
displays a Textbox.
Some Notable Properties:
Some important properties in the Behavior section of the Properties Window for TextBoxes.
TextAlign: Allows to align the text from three possible options. The default value is left and you can set the
alignment of text to right or center.
Scrollbars: Allows to add a scrollbar to a Textbox. Very useful when the TextBox is multiline. You have
four options with this property. Options are are None, Horizontal, Vertical and Both. Depending on the size
of the TextBox anyone of those can be used.
TextBox Event
The default event of the TextBox is the TextChanged Event which looks like this in code:
End Sub
Drag two TextBoxes (TextBox1, TextBox2) and a Button (Button1) from the toolbox.
Set the PasswordChar property of TextBox2 to *. Setting that will make the text entered in TextBox2 to be
displayed as *. We want to display what is entered in TextBox2 in TextBox1. The code for that looks like
this:
When you run the program and enter some text in TextBox2, text will be displayed as *. When you click
the Button, the text you entered in TextBox2 will be displayed as plain text in TextBox1.
We can make sure that a TextBox can accept only characters or numbers which can restrict accidental
operations. For example, adding two numbers of the form 27+2J cannot return anything. To avoid such
kind of operations we use the KeyPress event of the TextBox.
Code that allows you to enter only double digits in a TextBox looks like this:
CheckBox
CheckBoxes are those controls which gives us an option to select, say, Yes/No or True/False. A checkbox is
clicked to select and clicked again to deselect some option. When a checkbox is selected a check (a tick
mark) appears indicating a selection. The CheckBox control is based on the TextBoxBase class which is
based on the Control class. Below is the image of a Checkbox.
Notable Properties
Important properties of the CheckBox in the Appearance section of the properties window are:
Appearance: Default value is Normal. Set the value to Button if you want the CheckBox to be displayed as
a Button.
BackgroundImage: Used to set a background image for the checkbox.
CheckAlign: Used to set the alignment for the CheckBox from a predefined list.
Checked: Default value is False, set it to True if you want the CheckBox to be displayed as checked.
CheckState: Default value is Unchecked. Set it to True if you want a check to appear. When set to
Indeterminate it displays a check in gray background.
FlatStyle: Default value is Standard. Select the value from a predefined list to set the style of the checkbox.
Important property in the Behavior section of the properties window is the ThreeState property which is set
to False by default. Set it to True to specify if the Checkbox can allow three check states than two.
CheckBox Event
The default event of the CheckBox is the CheckedChange event which looks like this in code:
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
End Sub
Lets work with an example. Drag a CheckBox (CheckBox1), TextBox (TextBox1) and a Button (Button1)
from the Toolbox.
Label, LinkLabel
Label
Labels are those controls that are used to display text in other parts of the application. They are based on
the Control class.
Notable property of the label control is the text property which is used to set the text for the label.
Label Event
The default event of Label is the Click event which looks like this in code:
End Sub
LinkLabel
LinkLabel is similar to a Label but they display a hyperlink. Even multiple hyperlinks can be specified in
the text of the control and each hyperlink can perform a different task within the application. They are
based on the Label class which is based on the Control class.
Notable properties of the LinkLabel control are the ActiveLinkColor, LinkColor and LinkVisited which are
used to set the link color.
LinkLabel Event
The default event of LinkLabel is the LinkClicked event which looks like this in code:
End Sub
RadioButton
RadioButtons are similar to CheckBoxes but RadioButtons are displayed as rounded instead of boxed as
with a checkbox. Like CheckBoxes, RadioButtons are used to select and deselect options but they allow us
to choose from mutually exclusive options. The RadioButton control is based on the ButtonBase class
which is based on the Control class. A major difference between CheckBoxes and RadioButtons is,
RadioButtons are mostly used together in a group. Below is the image of a RadioButton.
Important properties of the RadioButton in the Appearance section of the properties window are:
Appearance: Default value is Normal. Set the value to Button if you want the RadioButton to be displayed
as a Button.
BackgroundImage: Used to set a background image for the RadioButton.
CheckAlign: Used to set the alignment for the RadioButton from a predefined list.
Checked: Default value is False, set it to True if you want the RadioButton to be displayed as checked.
FlatStyle: Default value is Standard. Select the value from a predefined list to set the style of the
RadioButton.
RadioButton Event
The default event of the RadioButton is the CheckedChange event which looks like this in code:
End Sub
Drag a RadioButton (RadioButton1), TextBox (TextBox1) and a Button (Button1) from the Toolbox.
ListBox
The ListBox control displays a list of items from which we can make a selection. We can select one or more
than one of the items from the list. The ListBox control is based on the ListControl class which is based on
the Control class. The image below displays a ListBox.
Notable Properties of the ListBox
HorizontalScrollbar: Displays a horizontal scrollbar to the ListBox. Works when the ListBox has
MultipleColumns.
MultiColumn: The default value is set to False. Set it to True if you want the list box to display multiple
columns.
ScrollAlwaysVisible: Default value is set to False. Setting it to True will display both Vertical and
Horizontal scrollbar always.
SelectionMode: Default value is set to one. Select option None if you do not any item to be selected. Select
it to MultiSimple if you want multiple items to be selected. Setting it to MultiExtended allows you to select
multiple items with the help of Shift, Control and arrow keys on the keyboard.
Sorted: Default value is set to False. Set it to True if you want the items displayed in the ListBox to be
sorted by alphabetical order.
Notable property in the Data section of the Properties window is the Items property. The Items property
allows us to add the items we want to be displayed in the list box. Doing so is simple, click on the ellipses
to open the String Collection Editor window and start entering what you want to be displayed in the
ListBox. After entering the items click OK and doing that adds all the items to the ListBox.
ListBox Event
The default event of ListBox is the SelectedIndexChanged which looks like this in code:
End Sub
Drag a TextBox and a ListBox control to the form and add some items to the ListBox with it's items
property.
Referring to Items in the ListBox
Items in a ListBox are referred by index. When items are added to the ListBox they are assigned an index.
The first item in the ListBox always has an index of 0 the next 1 and so on.
When you run the code and select an item from the ListBox, it's index is displayed in the textbox.
Add a Button to the form and place the following code in it's click event.
When you run the code and click the Button it will display the number of items available in the ListBox.
When you run the code and click an item in the ListBox that item will be displayed in the TextBox.
You can remove all items or one particular item from the list box.
ComboBox
ComboBox is a combination of a TextBox and a ListBox. The ComboBox displays an editing field
(TextBox) combined with a ListBox allowing us to select from the list or to enter new text. ComboBox
displays data in a drop-down style format. The ComboBox class is derived from the ListBox class. Below
is the Image of a ComboBox.
The DropDownStyle property in the Appearance section of the properties window allows us to set the look
of the ComboBox. The default value is set to DropDown which means that the ComboBox displays the
Text set by it's Text property in the Textbox and displays it's items in the DropDownListBox below. Setting
it to simple makes the ComboBox to be displayed with a TextBox and the list box which doesn't drop
down. Setting it to DropDownList makes the ComboBox to make selection only from the drop down list
and restricts you from entering any text in the textbox.
We can sort the ComboBox with it's Sorted property which is set to False by Default.
ComboBox Event
The default event of ComboBox is SelectedIndexChanged which looks like this in code:
Drag a ComboBox and a TextBox control onto the form. To display the selection made in the ComboBox in
the Textbox the code looks like this:
You can remove all items or one particular item from the list box part of the ComboxBox. Code to remove
a particular item by it's Index number looks like this:
ADO .NET
Most applications need data access at one point of time making it a crucial component when working with
applications. Data access is making the application interact with a database, where all the data is stored.
Different applications have different requirements for database access. VB .NET uses ADO .NET (Active
X Data Object) as it's data access and manipulation protocol which also enables us to work with data on the
Internet. Let's take a look why ADO .NET came into picture replacing ADO.
Evolution of ADO.NET
The first data access model, DAO (data access model) was created for local databases with the built-in Jet
engine which had performance and functionality issues. Next came RDO (Remote Data Object) and ADO
(Active Data Object) which were designed for Client Server architectures but soon ADO took over RDO.
ADO was a good architecture but as the language changes so is the technology. With ADO, all the data is
contained in a recordset object which had problems when implemented on the network and penetrating
firewalls. ADO was a connected data access, which means that when a connection to the database is
established the connection remains open until the application is closed. Leaving the connection open for the
lifetime of the application raises concerns about database security and network traffic. Also, as databases
are becoming increasingly important and as they are serving more people, a connected data access model
makes us think about its productivity. For example, an application with connected data access may do well
when connected to two clients, the same may do poorly when connected to 10 and might be unusable when
connected to 100 or more. Also, open database connections use system resources to a maximum extent
making the system performance less effective.
Why ADO.NET?
To cope up with some of the problems mentioned above, ADO .NET came into existence. ADO .NET
addresses the above mentioned problems by maintaining a disconnected database access model which
means, when an application interacts with the database, the connection is opened to serve the request of the
application and is closed as soon as the request is completed. Likewise, if a database is Updated, the
connection is opened long enough to complete the Update operation and is closed. By keeping connections
open for only a minimum period of time, ADO .NET conserves system resources and provides maximum
security for databases and also has less impact on system performance. Also, ADO .NET when interacting
with the database uses XML and converts all the data into XML format for database related operations
making them more efficient.
Data Access in ADO.NET relies on two components: DataSet and Data Provider.
DataSet
The dataset is a disconnected, in-memory representation of data. It can be considered as a local copy of the
relevant portions of the database. The DataSet is persisted in memory and the data in it can be manipulated
and updated independent of the database. When the use of this DataSet is finished, changes can be made
back to the central database for updating. The data in DataSet can be loaded from any valid data source like
Microsoft SQL server database, an Oracle database or from a Microsoft Access database.
Data Provider
The Data Provider is responsible for providing and maintaining the connection to the database. A
DataProvider is a set of related components that work together to provide data in an efficient and
performance driven manner. The .NET Framework currently comes with two DataProviders: the SQL Data
Provider which is designed only to work with Microsoft's SQL Server 7.0 or later and the OleDb
DataProvider which allows us to connect to other types of databases like Access and Oracle. Each
DataProvider consists of the following component classes:
A connection object establishes the connection for the application with the database. The command object
provides direct execution of the command to the database. If the command returns more than a single value,
the command object returns a DataReader to provide the data. Alternatively, the DataAdapter can be used
to fill the Dataset object. The database can be updated using the command object or the DataAdapter.
Component classes that make up the Data Providers
The Connection object creates the connection to the database. Microsoft Visual Studio .NET provides two
types of Connection classes: the SqlConnection object, which is designed specifically to connect to
Microsoft SQL Server 7.0 or later, and the OleDbConnection object, which can provide connections to a
wide range of database types like Microsoft Access and Oracle. The Connection object contains all of the
information required to open a connection to the database.
The Command object is represented by two corresponding classes: SqlCommand and OleDbCommand.
Command objects are used to execute commands to a database across a data connection. The Command
objects can be used to execute stored procedures on the database, SQL commands, or return complete
tables directly. Command objects provide three methods that are used to execute commands on the
database:
ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE or DELETE
The DataReader object provides a forward-only, read-only, connected stream recordset from a database.
Unlike other components of the Data Provider, DataReader objects cannot be directly instantiated. Rather,
the DataReader is returned as the result of the Command object's ExecuteReader method. The
SqlCommand.ExecuteReader method returns a SqlDataReader object, and the
OleDbCommand.ExecuteReader method returns an OleDbDataReader object. The DataReader can provide
rows of data directly to application logic when you do not need to keep the data cached in memory.
Because only one row is in memory at a time, the DataReader provides the lowest overhead in terms of
system performance but requires the exclusive use of an open Connection object for the lifetime of the
DataReader.
The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is essentially the
middleman facilitating all communication between the database and a DataSet. The DataAdapter is used
either to fill a DataTable or DataSet with data from the database with it's Fill method. After the memory-
resident data has been manipulated, the DataAdapter can commit the changes to the database by calling the
Update method. The DataAdapter provides four properties that represent database commands:
SelectCommand
InsertCommand
DeleteCommand
UpdateCommand
When the Update method is called, changes in the DataSet are copied back to the database and the
appropriate InsertCommand, DeleteCommand, or UpdateCommand is executed.
In this section we will work with databases in code. We will work with ADO .NET objects in code to create
connections and read data using the data reader. We will see how to connect using our own connection
objects, how to use the command object and so on. The namespace that needs to be imported when working
with SQL Connections is System.Data.SqlClient. This section works with common database operations like
insert, select, update and delete commands.
When working with SQL Server the classes with which we work are described below.
DataReaders
A DataReader is a lightweight object that provides read-only, forward-only data in a very fast and efficient
way. Using a DataReader is efficient than using a DataAdapter but it is limited. Data access with
DataReader is
read-only, meaning, we cannot make any changes (update) to data and forward-only, which means we
cannot go back to the previous record which was accessed. A DataReader requires the exclusive use of an
active connection for the entire time it is in existence. We instantiate a DataReader by making a call to a
Command object's ExecuteReader command. When the DataReader is first returned it is positioned before
the first record of the result set. To make the first record available we need to call the Read method. If a
record is available, the Read method moves the DataReader to next record and returns True. If a record is
not available the Read method returns False. We use a While Loop to iterate through the records with the
Read method.
Sample Code
The following code displays data from Discounts table in Pubs sample database.
Imports System.Data.SqlClient
Public Class Form1 Inherits System.Windows.Forms.Form
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As New SqlDataReader()
'declaring the objects
End Class
Inserting Records
The following code inserts a Record into the Jobs table in Pubs sample database. Drag a button onto the
form and place the following code.
Imports System.Data.SqlClient
Public Class Form2 Inherits System.Windows.Forms.Form
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim ra as Integer
'integer holds the number of records inserted
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'you need to provide password for sql server
myConnection.Open()
myCommand = New SqlCommand("Insert into Jobs values 12,'IT Manager',100,300,_
myConnection)
ra=myCommand.ExecuteNonQuery()
MessageBox.Show("New Row Inserted" & ra)
myConnection.Close()
End Sub
End Class
Deleting a Record
We will use Authors table in Pubs sample database to work with this code. Drag a button onto the form and
place the following code.
Imports System.Data.SqlClient
Public Class Form3 Inherits System.Windows.Forms.Form
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim ra as Integer
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'you need to provide password for sql server
myConnection.Open()
myCommand = New SqlCommand("Delete from Authors where city='Oakland'",_
myConnection)
'since no value is returned we use ExecuteNonQuery
ra=myCommand.ExecuteNonQuery()
MessageBox.Show("Records affected" & ra)
myConnection.Close()
End Sub
End Class
Updating Records
We will update a row in Authors table. Drag a button onto the form and place the following code.
Imports System.Data.SqlClient
Public Class Form4 Inherits System.Windows.Forms.Form
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim ra as Integer
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'you need to provide password for sql server
myConnection.Open()
myCommand = New SqlCommand("Update Authors Set city='Oakland' where city=_
'San Jose' ",myConnection)
ra=myCommand.ExecuteNonQuery()
MessageBox.Show("Records affected" & ra)
myConnection.Close()
End Sub
End Class
LIST OF EXPERIMENTS
2) Write a program in visual basic to get two numbers from the user with the help
of input box and print them after swapping.
3) Write a program in visual basic to get two numbers from the user with the help
of input box and print greatest of two numbers.
4) Write a program in visual basic to get the first name & last name from the user
& concatenate them & print full name in message box.
5) Write a program in visual basic.Net to get one number & check whether the
number is prime or not.
6) Write a program in visual basic.Net to get one number and calculate the factorial of that
number.
10) Write a program in visual basic.Net to change back color of form using Radio
button.
11) Write a program in visual basic.Net to select Month from the combo box &
print the number of days in the text box.
12) Write a program in visual basic.Net to Search Items in the List Box.
13) Write a program in visual basic.Net to validate the Text Box in a Form.
14) Write a program in visual basic.Net to validate the Text Box in a Form & accept
only character.
15) Write a program in visual basic.Net to validate the Text Box in a Form & accept
only number.
19) Write a program in visual basic.Net for Updation using Ms.Access in a personal
Detail.
20) Write a program in visual basic.Net for Deletion using Ms.Access in a personal
Detail.
EXPERIMENT NO. 01
1) Write a program in visual basic.Net to Print Welcome to the World of
Visual Basic.Net in the message box.
Solution: -
Coding
Public Class Form1
Inherits System.Windows.Forms.Form
End Sub
End Class
EXPERIMENT NO. 02
2) Write a program in visual basic to get two numbers from the user with the help of
input box and print them after swapping.
Solution: -
Coding
Option Explicit
EXPERIMENT NO. 03
3) Write a program in visual basic to get two numbers from the user with the help of
input box and print the greatest of two numbers.
Solution: -
Coding
Option Explicit
EXPERIMENT NO. 04
4) Write a program in visual basic to get the first name & last name from the
user & concatenate them & print full name in message box.
Solution: -
Coding:
Public Class Form1
Inherits System.Windows.Forms.Form
5) Write a program in visual basic.Net to get one number & check whether
the number is prime or not.
Solution: -
Coding:
Public Class Form1
Inherits System.Windows.Forms.Form
End Sub
End Class
EXPERIMENT NO. 06
6) Write a program in visual basic.Net to get one number and calculate the factorial of that
number.
Solution: -
Coding:
Public Class Form1
Inherits System.Windows.Forms.Form
Solution: -
Coding:
Public Class Form1
Inherits System.Windows.Forms.Form
End Sub
End Class
EXPERIMENT NO. 08
8) Write a program in visual basic.Net for calculating Addition, Substraction, and
Multiplication & Division using Select case.
Solution: -
Coding:
Public Class Form1
Inherits System.Windows.Forms.Form
Solution: -
Coding:
Public Class Form1
Inherits System.Windows.Forms.Form
CheckBox1.CheckState = CheckState.Checked
TextBox1.Text = "Checked Box is Selected"
End Sub
CheckBox2.CheckState = CheckState.Unchecked
TextBox1.Text = "UnChecked Box is Selected"
End Sub
Private Sub CheckBox3_CheckedChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
CheckBox3.CheckedChanged
CheckBox3.CheckState = CheckState.Indeterminate
TextBox1.Text = "Indeterminate Box is Selected"
End Sub
End Class
EXPERIMENT NO. 10
10) Write a program in visual basic.Net to change back color of form using Radio
button.
Solution: -
Coding:
Public Class Form1
Inherits System.Windows.Forms.Form
Me.BackColor = Me.BackColor.AliceBlue
End Sub
Me.BackColor = Me.BackColor.Cyan
End Sub
Solution: -
Coding:
TextBox1.Text = 31
TextBox1.Text = 29
Else
TextBox1.Text = 30
End If
End Sub
End Class
EXPERIMENT NO. 12
12) Write a program in visual basic.Net to Search Items in the List Box.
Solution: -
Coding:
Public Class Form1
Inherits System.Windows.Forms.Form
ListBox1.SelectedIndex = ListBox1.FindString(Trim(TextBox1.Text))
End Sub
End Class
EXPERIMENT NO. 13
13) Write a program in visual basic.Net to validate the Text Box in a Form.
Solution: -
Coding:
If TxtName.Text.Length = 0 Then
MessageBox.Show("Name Cannot not be Empty")
TxtName.Focus()
Else
txtAddress.Focus()
End If
End Sub
If txtAddress.Text.Length = 0 Then
MessageBox.Show("Address Cannot be Empty")
txtAddress.Focus()
End If
End Sub
End Class
EXPERIMENT NO. 14
14) Write a program in visual basic.Net to validate the Text Box in a Form &
accept only character.
Solution: -
Coding:
Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub TxtName_Validating(ByVal sender As Object, ByVal e
As System.ComponentModel.CancelEventArgs) Handles
TxtName.Validating
Dim i As Integer
For i = 0 To TxtName.Text.Length - 1
If (Char.IsNumber(TxtName.Text, i)) Then
MessageBox.Show("Only Alphabets Allowed")
e.Cancel = True
TxtName.Text = ""
End If
Next
End Sub
EXPERIMENT NO. 15
15) Write a program in visual basic.Net to validate the Text Box in a Form &
accept only number.
Solution: -
Coding:
Public Class Form1
Inherits System.Windows.Forms.Form
Solution: -
Coding:
Public Class Form1
Inherits System.Windows.Forms.Form
Catch ex As Exception
Finally
MessageBox.Show("The Multiplication of num1 and num2 is ",
number3)
End Try
End Sub
End Class
EXPERIMENT NO. 17
17) Write a program in visual basic.Net for insertion using Ms.Access in a
Personal Details.
Solution: -
Coding:
Imports System.Data.OleDb
Public Class Form1
Inherits System.Windows.Forms.Form
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\personal_Details.mdb;Persist Security Info=False"
cmd.Connection = cn
cn.Open()
End Sub
Coding:
Imports System.Data.OleDb
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\personal_Details.mdb;Persist Security Info=False"
cmd.Connection = cn
cn.Open()
str = "Select * from table1"
cmd.CommandText = str
rs = cmd.ExecuteReader
Do While (rs.Read())
ComboBox1.Items.Add(rs(0))
Loop
rs.Close()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ComboBox1.SelectedIndexChanged
Solution: -
Coding:
Imports System.Data.OleDb
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\personal_Details.mdb;Persist Security Info=False"
cmd.Connection = cn
cn.Open()
str = "Select * from table1"
cmd.CommandText = str
rs = cmd.ExecuteReader
Do While (rs.Read())
ComboBox1.Items.Add(rs(0))
Loop
rs.Close()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ComboBox1.SelectedIndexChanged
Solution: -
Coding:
Imports System.Data.OleDb
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\personal_Details.mdb;Persist Security Info=False"
cmd.Connection = cn
cn.Open()
str = "Select * from table1"
cmd.CommandText = str
rs = cmd.ExecuteReader
Do While (rs.Read())
ComboBox1.Items.Add(rs(0))
Loop
rs.Close()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ComboBox1.SelectedIndexChanged
cmd.CommandText = s
cmd.ExecuteNonQuery()
MessageBox.Show("One Record Deleted")
End Sub
End Class
ASSIGNMENTS IN VISUAL BASIC.NET
1) Write a program in visual basic.Net to Print text placed in the text box using
message box.
2) Write a program in visual basic.net to get two numbers from the user with the
help of input box and print the lowest of two numbers.
3) Write a program in visual basic.net to get two numbers from the user with the
help of input box and print greatest of 5 numbers.
4) Write a program in visual basic to get the first name & last name from the user &
concatenate them & print full name in message box & also print the length of the
string.
5) Write a program in visual basic.Net to get one number & check whether the
number is perfect square or not.
6) Write a program in visual basic.Net to get one number and calculate the reverse of that
number.
7) Write a program in visual basic. Net to take 1 number and check whether the number is
Armstrong or not.
8) Write a program in visual basic.Net to change back color of text box using Radio
button.
10) Write a program in visual basic.Net for Searching using Ms.Access in a Library
Detail.
VIVA QUESTIONS