0% found this document useful (0 votes)
356 views115 pages

IT 6th MAIN VB - Net Manual

The document provides an overview of the key changes and new features in Visual Basic .NET compared to Visual Basic 6.0. Some of the major changes discussed include VB.NET now being a fully object-oriented programming language that supports concepts like inheritance, polymorphism, and encapsulation. It also discusses how VB.NET uses the .NET framework and supports additional application types like web and console applications. The document outlines some problems with VB6.0 like lack of threading and exceptions handling, and how VB.NET addresses these issues.

Uploaded by

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

IT 6th MAIN VB - Net Manual

The document provides an overview of the key changes and new features in Visual Basic .NET compared to Visual Basic 6.0. Some of the major changes discussed include VB.NET now being a fully object-oriented programming language that supports concepts like inheritance, polymorphism, and encapsulation. It also discusses how VB.NET uses the .NET framework and supports additional application types like web and console applications. The document outlines some problems with VB6.0 like lack of threading and exceptions handling, and how VB.NET addresses these issues.

Uploaded by

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

Lab Manual

Visual Basic. Net


Introduction
Visual Basic... A name everybody knows for a rich, easy and GUI based programming language, making
each & every task easier and improves programmer's productivity. VB has won the best RAD ( Rapid
Application Development ) Tool award for three times and still keeping itself at top.

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.

Briefly on some changes:

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

1. No capabilities for multithreading.


2. Lack of implementation inheritance and other object oriented features.
3. Poor error handling capabilities.
4. Poor integration with other languages such as C++.
5. No effective user interface for Internet based applications.

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.

Why Object Oriented approach?

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.

Some important features of Object Oriented programming are as follows:

o Emphasis on data rather than procedure


o Programs are divided into Objects
o Data is hidden and cannot be accessed by external functions
o Objects can communicate with each other through functions
o New data and functions can be easily added whenever necessary
o Follows bottom-up approach

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.

Data Abstraction and Encapsulation

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

Object-Oriented Programming has the following advantages over conventional approaches:

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 and Objects

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

Public Class Test


'creating a class named Test
Sub disp()
'a method named disp in the class
Write("Welcome to OOP")
End Sub
End Class

Output of above code is the image below.


Fields, Properties, Methods and Events

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:

Public Class House


Public Rooms as Integer
End Class

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

Public Class Country


Public Sub Area()
Write("--------")
End Sub
Public Sub population()
Write("---------")
End Sub
End Class

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()

Dim con As New Constructor(10)


WriteLine(con.display())
'storing a value in the constructor by passing a value(10) and calling it with the
'display method
Read()

End Sub

End Module
Public Class Constructor
Public x As Integer

Public Sub New(ByVal value As Integer)


'constructor
x = value
'storing the value of x in constructor
End Sub

Public Function display() As Integer


Return x
'returning the stored value
End Function

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

Public Class Destructor

Protected Overrides Sub Finalize()


Write("hello")
Read()
End Sub

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:

Public Class One


---
---
End Class

Public Class Two


Inherits One
---
---
End Class

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

Public Class One


'base class
Public i As Integer = 10
Public j As Integer = 20

Public Function add() As Integer


Return i + j
End Function

End Class
Public Class Two
Inherits One
'derived class. class two inherited from class one
Public k As Integer = 100

Public Function sum() As Integer


'using the variables, function from base class and adding more functionality
Return i + j + k
End Function

End Class

Output of above code is sum of i, j, k as shown in the image below.

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.

The following code demonstrates the implementation of Polymorphism.

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

Public Class One


Public i, j, k As Integer

Public Function add(ByVal i As Integer) As Integer


'function with one argument
Return i
End Function

Public Function add(ByVal i As Integer, ByVal j As Integer) As Integer


'function with two arguments
Return i + j
End Function

Public Function add(ByVal i As Integer, ByVal j As Integer, ByVal k As Integer) As Integer


'function with three arguments
Return i + j + k
End Function

End Class

Output of the above code is shown in the image below.

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 Interface Test


'creating an Interface named Test
Sub disp()
Function Multiply() As Double
'specifying two methods in an interface
End Interface

Public Class One


Implements Test
'implementing interface in class One

Public i As Double = 12
Public j As Double = 12.17

Sub disp() Implements Test.disp


'implementing the method specified in interface
WriteLine("sum of i+j is" & i + j)
Read()
End Sub

Public Function multiply() As Double Implements Test.Multiply


'implementing the method specified in interface
WriteLine(i * j)
Read()
End Function

End Class

Public Class Two


Implements Test
'implementing the interface in class Two

Public a As Double = 20
Public b As Double = 32.17

Sub disp() Implements Test.disp


WriteLine("Welcome to Interfaces")
Read()
End Sub

Public Function multiply() As Double Implements Test.Multiply


WriteLine(a * b)
Read()
End Function

End Class

Output of above code is the image below.

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.

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

Implementing Abstract Class

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

Public MustInherit Class AbstractClass


'declaring an abstract class with MustInherit keyword
Public MustOverride Function Add() As Integer
Public MustOverride Function Mul() As Integer
'declaring two abstract members with MustOverride keyword
End Class

Public Class AbstractOne


Inherits AbstractClass
'implementing the abstract class by inheriting
Dim i As Integer = 20
Dim j As Integer = 30
'declaring two integers

Public Overrides Function Add() As Integer


Return i + j
End Function
'implementing the add method

Public Overrides Function Mul() As Integer


Return i * j
End Function
'implementing the mul method

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.

Briefly on some changes:

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.

Some Namespaces and their use:

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.

Example on a Console Application

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.

Commenting the Code

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

Data Types, Access Specifiers


Data Types in VB .NET

The Data types available in VB .NET, their size, type, description are summarized in the table below.

Data Type Size in Bytes Description Type


Byte 1 8-bit unsigned integer System.Byte
16-bit Unicode
Char 2 System.Char
characters
Integer 4 32-bit signed integer System.Int32
64-bit floating point
Double 8 System.Double
variable
Long 8 64-bit signed integer System.Int64
Short 2 16-bit signed integer System.Int16
32-bit floating point
Single 4 System.Single
variable
String Varies Non-Numeric Type System.String
Date 8 System.Date
Boolean 2 Non-Numeric Type System.Boolean
Object 4 Non-Numeric Type System.Object
128-bit floating point
Decimal 16 System.Decimal
variable

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.

Example of a Sub Procedure

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

Public Function Add() As Integer


'declaring a function add
Dim i, j As Integer
'declaring two integers and assigning values to them
i = 10
j = 20
Return (i + j)
'performing the sum of two integers and returning it's value
End Function

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:

Public Function Add(ByVal x1 as Integer, ByVal y1 as Integer)


------------
Implementation
------------
End Function

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

Understanding the Syntax

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.

The syntax of the Select Case statement looks like this:

Select Case testexpression


[Case expressionlist-n
[statements-n]] . . .
[Case Else elsestatements]
End Select

Example

Imports System.Console
Module Module1

Sub Main()
Dim keyIn As Integer
WriteLine("Enter a number between 1 and 4")
keyIn = Val(ReadLine())

Select Case keyIn


Case 1
WriteLine("You entered 1")
Case 2
WriteLine("You entered 2")
Case 3
WriteLine("You entered 3")
Case 4
WriteLine("You entered 4")
End Select

End Sub

End Module

The image below displays output from above code.

The image below displays output from above code.


Loops

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:

For index=start to end[Step step]


[statements]
[Exit For]
[statements]
Next[index]

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.

Example on For loop

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

The image below displays output from above code.


While loop

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

Example on While loop

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

The image below displays output from above code.

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

The image below displays output from above code.

Below is the list of conversion functions which we can use in VB .NET.

CBool - use this function to convert to Bool data type


CByte - use this function to convert to Byte data type
CChar - use this function to convert to Char data type
CDate - use this function to convert to Date type
CDbl - use this function to convert to Double data type
CDec - use this function to convert to Decimal data type
CInt - use this function to convert to Integer data type
CLng - use this function to convert to Long data type
CObj - use this function to convert to Object type
CShort - use this function to convert to Short data type
CSng - use this function to convert to Single data type
CString - use this function to convert to String data type
Attributes

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.

File Extensions in VB .NET

The files and their extensions which are created as part of the Windows Application Project and their
meaning are summarized below:

.vbproj->A Visual Basic project


Form1.vb->A form's code
AssemblyInfo.VB->Information about an assembly, includes version information
.vbproj.user->Stores project user options
.sln->Solution file which stores solution's configuration
.suo-> Stores Solution user options
Form1.resx.NET->XML based resource template
bin directory->Directory for binary executables
obj directory->Directory for debugging binaries

Language Terminology

Briefly on some terminology when working with the language:

Module: Used to hold code


Variable: A named memory location of a specific data type used to hold some value
Procedure: A callable series of statements which may or may not return a value
Sub-Procedure: A procedure with no return value
Function: A procedure with return value
Methods: A procedure built into the class
Constructor: Special method used to initialize and customize the object. It has the same name as the class
Class: An OOP class which contains data and code
Object: An instance of a class
Arrays: Programming constructs that lets us access data by numeric index
Attributes: They are the items that specify information about other items being used in VB. NET

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

Logical / Bitwise Operators


The logical operators compare Boolean expressions and return a Boolean result. In short,
logical operators are expressions which return a true or false result over a conditional
expression. The table below summarizes them:

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

The image below displays output from above code.


Concatenation Operators

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

The image below displays output from above code.


Comparison Operators

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.

Logical / Bitwise Operators

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, Exception Handling

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.

The following code demonstrates arrays.

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

Understanding the Code

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.

Dim Test(10) as Integer


ReDim Test(25) as Integer
'Reinitializing the array

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:

Dim Test() as Integer={1,3,5}


'declares an array an initializes it with three members
ReDim Preserve Test(25)
'resizes the array and retains the the data in elements 0 to 2

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.

Dim rectArray(4, 2) As Integer


'declares an array of 5 by 3 members which is a 15 member array
Dim rectArray(,) As Integer = {{1, 2, 3}, {12, 13, 14}, {11, 10, 9}}
'setting initial values
Visual Studio .NET IDE

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

One IDE for all .NET Projects

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.

Option to choose from Multiple Programming Languages

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.

When we open VS .NET from Start->Programs->Microsoft Visual Studio .NET->Microsoft Visual


Studio .NET the window that is displayed first is the Start Page which is shown below. The start Page
allows us to select from the most recent projects (last four projects) with which we worked or it can be
customized based on your preferences.
The Integrated Development Environment (IDE) shown in the image below is what we actually work with.
This IDE is shared by all programming languages in Visual Studio. You can view the toolbars towards the
left side of the image along with the Solution Explorer window towards the right.
New Project Dialogue Box

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.

ASP .NET Web Service: Allows to create XML 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.

Server Explorer Window

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 Designer Window

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.

Task List Window


The task list window displays all the tasks that VB .NET assumes we still have to finish. You can view the
task list window by selecting View->Show tasks->All or View->Other Windows->Task List from the main
menu. The image below shows that. As you can see from the image, the task list displayed "TextBox1 not
declared", "RichTextBox1 not declared". The reason for that message is, there were no controls on the form
and attempts where made to write code for a textbox and a richtextbox. Task list also displays syntax errors
and other errors you normally encounter during coding

Class View Window

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.

Object Explorer Window

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.

Image of a Windows Form.


Typically the Form looks like this in Code which is handled by the Framework.

Public Class Form1


Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Public Sub New()


MyBase.New()

'This call is required by the Windows Form Designer.


InitializeComponent()

'Add any initialization after the InitializeComponent() call

End Sub

'Form overrides dispose to clean up the component list.


Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Required by the Windows Form Designer


Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer


'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(496, 493)
Me.Name = "Form1"
Me.Text = "Form1"

End Sub

#End Region

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


MyBase.Load

End Sub
End Class

Windows Form Properties

Below are the properties of a Windows Form. Properties displayed below are categorized as seen in the
properties window.

Appearance Properties Description

BackColor Gets/Sets the background color for the form

BackgroundImage Get/Sets the background image in the form

Gets/Sets the cursor to be displayed when the user moves the mouse
Cursor
over the form

Font Gets/Sets the font for the form

ForeColor Gets/Sets the foreground color of the form

FormBorderStyle Gets/Sets the border style of the form

Gets/Sets the value indicating if the alignment of the control's


RightToLeft
elements is reversed to support right-to-left fonts

Text Gets/Sets the text associated with this form

Behavior Properties Description

AllowDrop Indicates if the form can accept data that the user drags and drops into it

ContextMenu Gets/Sets the shortcut menu for the form

Enabled Gets/Sets a value indicating if the form is enabled

ImeMode Gets/Sets the state of an Input Method Editor

Data Properties Description

DataBindings Gets the data bindings for a control


Tag Gets/Sets an object that contains data about a control

Design Properties Description

Name Gets/Sets name for the form

DrawGrid Indicates whether or not to draw the positioning grid

GridSize Determines the size of the positioning grid

Locked Gets/Sets whether the form is locked

SnapToGrid Indicates if the controls should snap to the positioning grid

Layout Properties Description

Indicates if the form adjusts its size to fit the height of the font used on the
AutoScale
form and scales its controls

AutoScroll Indicates if the form implements autoscrolling

AutoScrollMargin The margin around controls during auto scroll

AutoScrollMinSize The minimum logical size for the auto scroll region

DockPadding Determines the size of the border for docked controls

Location Gets/Sets the co-ordinates of the upper-left corner of the form

MaximumSize The maximum size the form can be resized to

MinimumSize The minimum size the form can be resized to

Size Gets/Sets size of the form in pixels

StartPosition Gets/Sets the starting position of the form at run time

WindowState Gets/Sets the form's window state

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

Language Indicates the current localizable language

Localizable Determines if localizable code will be generated for this object

Window Style
Description
Properties

ControlBox Gets/Sets a value indicating if a control box is displayed

HelpButton Determines whether a form has a help button on the caption bar

Icon Gets/Sets the icon for the form


Gets/Sets a value indicating if the form is a container for MDI child
IsMdiContainer
forms

Gets/Sets a value indicating if the maximize button is displayed in the


MaximizeBox
caption bar of the form

Menu Gets/Sets the MainMenu that is displayed in the form

Gets/Sets a value indicating if the minimize button is displayed in the


MinimizeBox
caption bar of the form

Opacity Determines how opaque or transparent the form is

Gets/Sets a value indicating if the form is displayed in the Windows


ShowInTaskbar
taskbar

SizeGripStyle Determines when the size grip will be displayed for the form

Gets/Sets a value indicating if the form should be displayed as the


TopMost
topmost form of the application

TransparencyKey A color which will appear transparent when painted on the form

Working with Forms

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.

Briefly on Properties (Categorized):

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:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_


Handles MyBase.Load

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.

Public Class Form1


Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Private Sub Form1_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
End Sub
End Class

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

It looks like this in code.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _


System.EventArgs) Handles Button1.Click
MsgBox("Welcome to Forms")
End Sub

or

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _


System.EventArgs) Handles Button1.Click
MessageBox.Show("Welcome to Forms")
End Sub

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.

Working with Multiple Forms

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:

Public Class Form1 Inherits System.Windows.Forms.Form


Dim other As New Form2()
'Creating a reference to Form2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
other.Show()
End Sub
Visual Inheritance with Forms

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, InputBox

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:

Public Class Form1 Inherits System.Windows.Forms.Form


Dim OwnedForm1 As New Form()

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e_


As System.EventArgs) Handles Button2.Click
Me.AddOwnedForm(OwnedForm1)
'adding an owned form to the current form
OwnedForm1.show()
'displaying the owned form
End Sub

The image below displays output from above code.


InputBox Function

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.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_


As System.EventArgs) Handles Button1.Click
Dim s As String = InputBox("Enter some text")
'storing the text entered in a string
TextBox1.Text = s
'displaying string in the textbox
End Sub

Handling Mouse Events in Forms

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:

Button: Specifies that the mouse button was pressed


Clicks: Specifies number of times the mouse button is pressed and released
X: The X-coordinate of the mouse click
Y: The Y-coordinate of the mouse click
Delta: Specifies a count of the number of detents (rotation of mouse wheel) the mouse wheel has rotated

Working with an Example

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

Public Class Form1 Inherits System.Windows.Forms.Form


'Windows Form Designer Generated Code
Private Sub Form1_Mousedown(ByVal sender As System.Object, ByVal e As _
System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
If e.Button = MouseButtons.Left Then
TextBox1.Text = "Mouse down at" + CStr(e.X) + " :" + CStr(e.Y)
'displaying the coordinates in TextBox1 when the mouse is pressed on the form
End If
End Sub

Private Sub Form1_MouseEnter(ByVal sender As System.Object, ByVal e_


As System.EventArgs) Handles MyBase.MouseEnter
TextBox2.Text = "Mouse Entered"
'displaying "mouse entered" in TextBox2 when the mouse pointer enters the form
End Sub

Private Sub Form1_MouseLeave(ByVal sender As System.Object, ByVal e_


As System.EventArgs) Handles MyBase.MouseLeave
TextBox3.Text = "Mouse Exited"
'displaying "mouse exited" in Textbox3 when the mouse pointer leaves the form
End Sub

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:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_


As System.EventArgs) Handles Button1.Click
Beep()
End Sub

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:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_


System.EventArgs) Handles Button1.Click
'You place the code here to perform action when Button is clicked
End Sub

Working with Buttons

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.

Important Properties of Button1 from Properties Window:

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.

Creating a Button in Code

Below is the code to create a button.

Public Class Form1 Inherits System.Windows.Forms.Form


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles_ MyBase.Load
Dim Button1 as New Button()
'declaring the button, Button1
Button1.Text="Creating a Button"
'setting the text to be displayed on the Button
Button1.Location=New Point(100,50)
'setting the location for the Button where it should be created
Button1.Size=New Size(75,23)
'setting the size of the Button
Me.Controls.Add(Button1)
'adding the Button that is created to the form
'the Me keyword is used to refer to the current object, in this case the Form
End Sub
End Class

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.

Enabled: Default value is True. To disable, set the property to False.


Multiline: Setting this property to True makes the TextBox multiline which allows to accept multiple lines
of text. Default value is False.
PasswordChar: Used to set the password character. The text displayed in the TextBox will be the character
set by the user. Say, if you enter *, the text that is entered in the TextBox is displayed as *.
ReadOnly: Makes this TextBox readonly. It doesn't allow to enter any text.
Visible: Default value is True. To hide it set the property to False.

Important properties in the Appearance section

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:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As _


System.EventArgs) Handles TextBox1.TextChanged

End Sub

Working With TextBoxes

Lets work with some examples to understand TextBoxes.

Drag two TextBoxes (TextBox1, TextBox2) and a Button (Button1) from the toolbox.

Code to Display some text in the TextBox


We want to display some text, say, "Welcome to TextBoxes", in TextBox1 when the Button is clicked.
The code looks like this:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_


As System.EventArgs) Handles Button1.Click
TextBox1.Text = "Welcome to TextBoxes"
End Sub

Code to Work with PassWord Character

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:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_


As System.EventArgs) Handles Button1.Click
TextBox1.Text = TextBox2.Text
End Sub

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.

Code to Validate User Input

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:

Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As_


System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If(e.KeyChar < "10" Or e.KeyChar > "100") Then
MessageBox.Show("Enter Double Digits")
End If
End Sub

Creating a TextBox in Code

Public Class Form1 Inherits System.Windows.Forms.Form


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles MyBase.Load
Dim TextBox1 as New TextBox()
TextBox1.Text="Hello Mate"
TextBox1.Location=New Point(100,50)
TextBox1.Size=New Size(75,23)
Me.Controls.Add(TextBox1)
End Sub
End Class

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

Working with CheckBoxes

Lets work with an example. Drag a CheckBox (CheckBox1), TextBox (TextBox1) and a Button (Button1)
from the Toolbox.

Code to display some text when the Checkbox is checked

Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
TextBox1.Text = "CheckBox Checked"
End Sub

Code to check a CheckBox's state

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_


System.EventArgs) Handles Button1.Click
If CheckBox1.Checked = True Then
TextBox1.Text = "Checked"
Else
TextBox1.Text = "UnChecked"
End If
End Sub

Creating a CheckBox in Code

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_


System.EventArgs) Handles_ MyBase.Load
Dim CheckBox1 As New CheckBox()
CheckBox1.Text = "Checkbox1"
CheckBox1.Location = New Point(100, 50)
CheckBox1.Size = New Size(95, 45)
Me.Controls.Add(CheckBox1)
End Sub

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:

Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_


Handles Label1.Click

End Sub

Creating a Label in Code

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_


Handles MyBase.Load Dim Label1 As New Label()
Label1.Text = "Label"
Label1.Location = New Point(135, 70)
Label1.Size = New Size(30, 30)
Me.Controls.Add(Label1)
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:

Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, _


ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)_
Handles LinkLabel1.LinkClicked

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:

Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object,_


ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged

End Sub

Working with Examples

Drag a RadioButton (RadioButton1), TextBox (TextBox1) and a Button (Button1) from the Toolbox.

Code to display some text when the RadioButton is selected

Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
TextBox1.Text = "RadioButton Selected"
End Sub

Code to check a RadioButton's state

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_


System.EventArgs) Handles Button1.Click
If RadioButton1.Checked = True Then
TextBox1.Text = "Selected"
Else
TextBox1.Text = "Not Selected"
End If
End Sub

Creating a RadioButton in Code

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_


System.EventArgs) Handles_ MyBase.Load
Dim RadioButton1 As New RadioButton()
RadioButton1.Text = "RadioButton1"
RadioButton1.Location = New Point(120,60)
RadioButton1.Size = New Size(100, 50)
Me.Controls.Add(RadioButton1)
End Sub

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

In the Behavior Section

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.

In the Data Section

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:

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

End Sub

Working with ListBoxes

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.

Code to display the index of an item

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox1.Text = ListBox1.SelectedIndex
'using the selected index property of the list box to select the index
End Sub

When you run the code and select an item from the ListBox, it's index is displayed in the textbox.

Counting the number of Items in a ListBox

Add a Button to the form and place the following code in it's click event.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _


As System.EventArgs) Handles Button1.Click
TextBox1.Text = ListBox1.Items.Count
'counting the number of items in the ListBox with the Items.Count
End Sub

When you run the code and click the Button it will display the number of items available in the ListBox.

Code to display the item selected from ListBox in a TextBox

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,_


ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox1.Text = ListBox1.SelectedItem
'using the selected item property
End Sub

When you run the code and click an item in the ListBox that item will be displayed in the TextBox.

Code to Remove items from a ListBox

You can remove all items or one particular item from the list box.

Code to remove a particular item

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _


As System.EventArgs) Handles Button1.Click
ListBox1.Items.RemoveAt(4)
'removing an item by specifying it's index
End Sub
Code to Remove all items

Private Sub Button1_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
'using the clear method to clear the list box
End Sub

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.

Notable properties of the 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.

We can add items to the ComboBox with it's Items property.

ComboBox Event

The default event of ComboBox is SelectedIndexChanged which looks like this in code:

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object,_


ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub

Working with ComboBoxes

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:

Removing items from a ComboBox

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:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_


System.EventArgs) Handles Button1.Click
ComboBox1.Items.RemoveAt(4)
'removing an item by specifying it's index
End Sub

Code to remove all items from the ComboBox

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_


System.EventArgs) Handles Button1.Click
ComboBox1.Items.Clear()
'using the clear method to clear the list box
End Sub

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.

The ADO.NET Data Architecture

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:

The Connection object which provides a connection to the database


The Command object which is used to execute a command
The DataReader object which provides a forward-only, read only, connected recordset
The DataAdapter object which populates a disconnected DataSet with data and performs update

Data access with ADO.NET can be summarized as follows:

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

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

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

ExecuteScalar: Returns a single value from a database query


ExecuteReader: Returns a result set by way of a DataReader object

The DataReader Object

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 Object

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.

Using DataReaders, SQL Server

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.

Working with SQL Server

When working with SQL Server the classes with which we work are described below.

The SqlConnection Class


The SqlConnection class represents a connection to SQL Server data source. We use OleDB connection
object when working with databases other than SQL Server. Performance is the major difference when
working with SqlConnections and OleDbConnections. Sql connections are said to be 70% faster than
OleDb connections.

The SqlCommand Class


The SqlCommand class represents a SQL statement or stored procedure for use in a database with SQL
Server.
The SqlDataAdapter Class
The SqlDataAdapter class represents a bridge between the dataset and the SQL Server database. It includes
the Select, Insert, Delete and Update commands for loading and updating the data.

The SqlDataReader Class


The SqlDataReader class creates a data reader to be used with SQL Server.

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

Code to Retrieve Data using Select Command

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

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_


Handles MyBase.Load
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'establishing connection. you need to provide password for sql server
Try
myConnection.Open()
'opening the connection
myCommand = New SqlCommand("Select * from discounts", myConnection)
'executing the command and assigning it to connection
dr = myCommand.ExecuteReader()
While dr.Read()
'reading from the datareader
MessageBox.Show("discounttype" & dr(0).ToString())
MessageBox.Show("stor_id" & dr(1).ToString())
MessageBox.Show("lowqty" & dr(2).ToString())
MessageBox.Show("highqty" & dr(3).ToString())
MessageBox.Show("discount" & dr(4).ToString())
'displaying the data from the table
End While
dr.Close()
myConnection.Close()
Catch e As Exception
End Try
End Sub

End Class

Using DataReaders, SQL Server

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

1) Write a program in visual basic.Net to Print Welcome to the World of Visual


Basic.Net in the message box.

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.

7) Write a program in visual basic. Net to generate a Fabonicci Series.

8) Write a program in visual basic.Net for calculating Addition, Substraction, and


Multiplication & Division using Select case.

9) Write a program in visual basic.Net to use check box on the form.

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.

16) Write a program in visual basic.Net using Exception Handling.


17) Write a program in visual basic.Net for insertion using Ms.Access in a Personal
Details.

18) Write a program in visual basic.Net for Searching using Ms.Access in a


personal Detail.

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

Private Sub Button1_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles Button1.Click

MessageBox.Show("Jaimatadi", "Welcome To The World Of Visual


Basic.Net", MessageBoxButtons.OK, MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1)

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

Public Class Form1


Inherits System.Windows.Forms.Form

Private Sub Button1_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles Button1.Click

Dim i As Integer, j As Integer, swap As Integer


i = InputBox("Please Enter the value for i in integer")
j = InputBox("Please Enter the value for j in integer")
swap = i
i=j
j = swap
MessageBox.Show("The Value of i after swapping is " & i & "
and the value of j after swapping is " & j, "Result After
Swapping", MessageBoxButtons.OK,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1)
End Sub
End Class

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

Public Class Form1


Inherits System.Windows.Forms.Form

Private Sub Button1_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles Button1.Click

Dim i As Integer, j As Integer, swap As Integer


i = InputBox("Please Enter the value for i in integer")
j = InputBox("Please Enter the value for j in integer")
if i>j then
MessageBox.Show("The Value of i " & i & “ is greatest",
MessageBoxButtons.OK,MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1)
Else
MessageBox.Show("The Value of j " & j & “ is greatest",
MessageBoxButtons.OK,MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1)
End Sub
End Class

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

Private Sub Button1_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles Button1.Click

Dim i As String, j As String


i = TextBox1.Text
j = TextBox2.Text
MessageBox.Show("The Required Full Name is " & i & " " & j,
"Result After Swapping", MessageBoxDefaultButton.Button1)
End Sub
End Class
EXPERIMENT NO. 05

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

Private Sub Button1_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles Button1.Click

Dim n As Integer, i As Integer, c As Integer


c=0
n = TextBox1.Text
For i = 2 To n - 1
If n Mod i = 0 Then
c=c+1
End If
Next
If c = 0 Then
MessageBox.Show("The Required Number is prime")
Else
MessageBox.Show("The Required Number is composite")
End If

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

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click
Dim n As Integer, i As Integer, fact As Integer
fact = 1
n = Val(TextBox1.Text)
For i = 1 To n
fact = fact * i
Next
MessageBox.Show("The Required Factorial is " & fact)
End Sub
End Class
EXPERIMENT NO. 07

7) Write a program in visual basic. Net to generate a Fabonicci Series.

Solution: -

Coding:
Public Class Form1
Inherits System.Windows.Forms.Form

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click
Dim a As Integer, b As Integer, c As Integer, n As Integer, i
As Integer
a=0
b=1
n = Val(TextBox1.Text)
For i = 1 To n - 2
c=a+b
a=b
b=c
Print(c)
Next

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

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click
Dim a As Integer, b As Integer, c As Integer, d As Single
a = InputBox("Enter First Number")
b = InputBox("Enter Second Number")
c = InputBox("Enter your Choice")
Select Case c
Case 1
d=a+b
MessageBox.Show("The required Sum is " & d)
Case 2
d=a-b
MessageBox.Show("The required Sum is " & d)
Case 3
d=a/b
MessageBox.Show("The required Sum is " & d)
Case 4
d=a*b
MessageBox.Show("The required Sum is " & d)
Case Else
MessageBox.Show(“Invalid Choice”)
End Select
End Sub
EXPERIMENT NO. 9
9) Write a program in visual basic.Net to use check box on the form.

Solution: -

Coding:
Public Class Form1
Inherits System.Windows.Forms.Form

Private Sub CheckBox1_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
CheckBox1.CheckedChanged

CheckBox1.CheckState = CheckState.Checked
TextBox1.Text = "Checked Box is Selected"
End Sub

Private Sub CheckBox2_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
CheckBox2.CheckedChanged

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

Private Sub RadioButton1_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
RadioButton1.CheckedChanged

Me.BackColor = Me.BackColor.AliceBlue
End Sub

Private Sub RadioButton2_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
RadioButton2.CheckedChanged

Me.BackColor = Me.BackColor.Cyan
End Sub

Private Sub RadioButton3_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
RadioButton3.CheckedChanged
Me.BackColor = Me.BackColor.Yellow
End Sub
End Class
EXPERIMENT NO. 11
11) Write a program in visual basic.Net to select Month from the combo box &
print the number of days in the text box.

Solution: -

Coding:

Public Class Form1


Inherits System.Windows.Forms.Form

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
ComboBox1.SelectedIndexChanged

If ComboBox1.Text = "January" Or ComboBox1.Text = "March" Or


ComboBox1.Text = "July" Or ComboBox1.Text = "May" Or
ComboBox1.Text = "August" Or ComboBox1.Text = "October" Or
ComboBox1.Text = "December" Then

TextBox1.Text = 31

ElseIf ComboBox1.Text = "February" Then

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

Private Sub Button1_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles Button1.Click

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:

Public Class Form1


Inherits System.Windows.Forms.Form

Private Sub TxtName_Leave(ByVal sender As Object, ByVal e As


System.EventArgs) Handles TxtName.Leave

If TxtName.Text.Length = 0 Then
MessageBox.Show("Name Cannot not be Empty")
TxtName.Focus()
Else
txtAddress.Focus()
End If
End Sub

Private Sub txtAddress_Leave(ByVal sender As Object, ByVal e As


System.EventArgs) Handles txtAddress.Leave

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

Private Sub TxtName_Validated(ByVal sender As Object, ByVal e


As System.EventArgs) Handles TxtName.Validated
MessageBox.Show("Validation Completed Text Box Contains only
Alphabets")
End Sub
End Class

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

Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e


As System.EventArgs) Handles TextBox1.Leave

If Not IsNumeric(TextBox1.Text) Then


MessageBox.Show("Enter Only Numbers")
TextBox1.Text = ""
End If
End Sub
End Class
EXPERIMENT NO. 16

16) Write a program in visual basic.Net using Exception Handling.

Solution: -

Coding:
Public Class Form1
Inherits System.Windows.Forms.Form

Private Sub Button1_Click(ByVal sender As System.Object, ByVal


E As System.EventArgs) Handles Button1.Click
Dim number1, number2, number3 As Integer
number1 = 100000
number2 = 500000
Try
number3 = number1 * number2
Catch ex As OverflowException
Throw New OverflowException("The Number that results because
of multiplication is too large thereby causing an overflow", ex)

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

Dim cn As New OleDbConnection


Dim cmd As New OleDbCommand
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MyBase.Load

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

Private Sub Button1_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles Button1.Click
Dim s As String
s = "insert into Table1 values('" & Trim(TextBox1.Text) & "','" &
Trim(TextBox2.Text) & "')"
cmd.CommandText = s
cmd.ExecuteNonQuery()
MessageBox.Show("One Record Inserted")
End Sub
End Class
EXPERIMENT NO. 18
18) Write a program in visual basic.Net for Searching using Ms.Access in a
personal Detail.
Solution: -

Coding:
Imports System.Data.OleDb

Public Class Form1


Inherits System.Windows.Forms.Form

Dim cn As New OleDbConnection


Dim cmd As New OleDbCommand
Dim rs As OleDbDataReader

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles MyBase.Load

Dim str As String

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

Dim str As String


str = "Select * from table1"
cmd.CommandText = str
rs = cmd.ExecuteReader
Do While (rs.Read())
If rs(0) = ComboBox1.Text Then
TextBox1.Text = rs(1)
End If
Loop
rs.Close()
End Sub
End Class
EXPERIMENT NO. 19
19) Write a program in visual basic.Net for Updation using Ms.Access in a
personal Detail.

Solution: -

Coding:
Imports System.Data.OleDb

Public Class Form1


Inherits System.Windows.Forms.Form

Dim cn As New OleDbConnection


Dim cmd As New OleDbCommand
Dim rs As OleDbDataReader

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles MyBase.Load

Dim str As String

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

Dim str As String


str = "Select * from table1"
cmd.CommandText = str
rs = cmd.ExecuteReader
Do While (rs.Read())
If rs(0) = ComboBox1.Text Then
TextBox1.Text = rs(1)
End If
Loop
rs.Close()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles Button1.Click
Dim s As String
S = "update Table1 set call_Number=” & trim(textbox2.text) &
“where ‘“ & combobox1.text & “’ = Name”
cmd.CommandText = s
cmd.ExecuteNonQuery()
MessageBox.Show("One Record Updated")
End Sub
End Class
EXPERIMENT NO. 20
20) Write a program in visual basic.Net for Deletion using Ms.Access in a
personal Detail.

Solution: -

Coding:
Imports System.Data.OleDb

Public Class Form1


Inherits System.Windows.Forms.Form

Dim cn As New OleDbConnection


Dim cmd As New OleDbCommand
Dim rs As OleDbDataReader

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles MyBase.Load

Dim str As String

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

Dim str As String


str = "Select * from table1"
cmd.CommandText = str
rs = cmd.ExecuteReader
Do While (rs.Read())
If rs(0) = ComboBox1.Text Then
TextBox1.Text = rs(1)
End If
Loop
rs.Close()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles Button1.Click
Dim s As String
S = "delete from Table1 where ” & combobox1.text & “’ =
Name & “’”

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.

9) Write a program in visual basic.Net for insertion using Ms.Access in a library


book Details.

10) Write a program in visual basic.Net for Searching using Ms.Access in a Library
Detail.
VIVA QUESTIONS

1) What is VB.net? Explain framework?

2) What is the difference between Vb.net & vb?

3) Write the different data types available in vb.net?

4) What is common language runtime?.

5) What is common type system?.

6) What is console application?

7) Why we can call vb.net as language independent?

8) What are the advantages of vb.net?

9) Explain the types of application we are built in vb.net..

You might also like