SlideShare a Scribd company logo
1 of 62
1.1 INTRODUCTION TO VISUAL BASIC
What is Visual Basic?
Visual Basic is a programming language designed to build applications with graphical user
interfaces (GUIs). The "Visual part refers to the method used to create the graphical user
interface (GUI). Rather than writing numerous lines of code to describe the appearance and
location of interface elements, you simply place pre-built objects on the screen. This part makes
Visual Basic a true RAD (Rapid Application Development) tool.
The "Basic" part refers to the BASIC (Beginners All-purpose Symbolic Instruction Code)
language, a language used by more programmers than any other language in the history of
computing. Visual Basic has evolved from the original BASIC language and now contains several
hundred statements, functions, and keywords, many of which relate directly to the Windows GUI.
Beginners can create useful applications by learning just a few of the keywords, yet the power of the
language allows professionals to accomplish anything that can be accomplished using any other
programming language.
Visual Basic supports a number of features that make it an excellent language for quickly
creating full-featured solutions. These features include the following:
 Data Access Features
By using data access features, developers can create databases, front-end applications and
scalable server-side components for most database formats, including Microsoft SQL server and
other enterprise-level databases.
 Internet Capabilities
Internet capabilities make it easy to provide access to documents and applications across the
Internet, or an Intranet, from with in the application and to create Internet server applications!
 RapidApplicationDevelopment (RAD)
A RAD system enables programmers to quickly build working programs. RAD systems
provide a number of tools to help build graphical user interfaces that would normally take a large
development effort. Visual Basic helps in reducing the development time by providing too ls such
as drag-and-drop design and code behind forms.
What is Visual Basic .NET?
Visual Basic .NET has been designed to create next-generation applications for the
Microsoft Windows Operating system and the Web. The Visual Basic language is now truly
object-oriented. Microsoft team has streamlined the whole language introducing various new
features. These new features open new doors for the Visual Basic developer to rapidly develop
scalable Web sites. The data tools now inherently support XML data also.
With Visual Basic .NET Microsoft has introduced two new interfaces Windows forms and
Web forms. These two interfaces are part of Visual Studio .NET, which is the IDE (Integrated
Development Environment) tool used for writing, debugging, compiling and executing the Visual
Basic applications. These interfaces provide an easy and efficient way for creating any type of
application, be it a standalone application running on single user PC or client server application or
enterprise n-tier applications or web centric applications. Visual Basic .NET is designed from
ground up to allow developers to easily develop and deploy complex Web applications.
1.2 NEED FOR VISUAL BASIC .NET
For nearly a decade, the Visual Basic language has been a popular programming language
for the Windows platform. It is easy to underestimate the impact that Visual Basic 1.0 had on the
Windows market - for the first time, writing windows applications was a simple and relatively
painless task, something with which even a novice programmer could easily create a simple
application. Similarly with the introduction of Visual Basic 4.0, it became simple to create COM
(Component Object Model) applications, which is nothing but Microsoft's specification for creating
pluggable objects, which can be reused in other applications. Even though COM applications can
be created using other languages like C++, since the language itself is complex many programmers
used Visual Basic for creating COM applications which is more simple to program. But with the
introduction of Visual Basic 5.0, using Visual Basic for COM programming became more popular
as it provided the ability to create ActiveX controls. Visual Basic 6.0 introduced Web classes,
windowless controls, data designers, new reporting designers, and the ability to create data sources.
Now Microsoft has introduced an advanced new generation of software that will drive the
Internet and its purpose is to make information available any time, any place, on any web-enabled
device, be it a desktop, laptop, palmtop or a cell phone. The driving force behind this is a shift in
recognizing the reality that applications are beginning to migrate from a standalone executable
sitting on a user's hard drive to "Web Services”, which is a distributed application delivered by a
web server across the Internet. A key part of Microsoft's thrust into this new web services space is
the .NET framework. The .NET framework is designed from the ground up to allow developers to
easily write and deploy complex web and Windows applications.
If Visual Basic is to retain relevance to users and help attract developers to the new Web
services platform, it must be a first class supporter of the .NET Framework. But in many cases
features needed to support the .NET framework conflict with existing features in the Visual Basic
language. Thus, the decision has been made by Microsoft to loose the bonds of backward
compatibility and take the language a step forward in the new evolution. The result is Visual Basic
.NET.
In short, we can say Microsoft has introduced a totally new language in Visual Basic .NET
which supports entirely "Microsoft's .NET strategy", which aims in providing a platform for
building internet based applications in a faster, efficient and much more reliable manner along with
interoperability with other languages providing a multi-language environment. So, now let us
briefly discuss the NET framework before we discuss the features of Visual Basic .NET.
1.3 UNDERSTANDINGTHE .NET FRAMEWORK
The Microsoft .NET strategy is an effort that tries to make the Internet a true distributed
computing platform by providing a framework that enables computers, devices, and services to
collaborate. In short we can say Microsoft .NET is Microsoft's strategy for delivering software as a
service. Microsoft .NET Platform is Microsoft's new environment for building, deploying and
running Web applications and other enterprise applications.
.NET is designed from the ground up to work well with the Internet by embracing Internet
standards, including supporting Web Services so programs can easily get data from multiple sites
and using XML extensively to facilitate data interchange between different computer systems.
.NET also makes accessing your data easier, and makes it far easier to write Web applications that
will run well on a wide variety of browsers and devices without having to rewrite the application
for each one. More over, the .NET runtime supports simplified and reliable installation and
upgrades for ease of use and increased reliability. The .NET Runtime's security and versioning
features also increase reliability and enable software to be sold as a service rather than a product.
The primary objective of .NET is to provide developers with a means to create interoperable
applications using "Web Services" from any sort of terminal, be it a PC, mobile phone, and so
forth.
What is .NET?
.NET is a set of common services, which can be used from a number of languages and have
the following specialties:
 These services are executed in the form of intermediate code that is independent of the
underlying architecture.
 They operate in a runtime (Common Language Runtime), which manages resources and
monitors application execution.
The .NET Framework is a multi-language environment for building, deploying, and running
Web Services and applications. The Microsoft .NET platform provides .NET infrastructure and
tools to build and operate a new generation of services. It consists of three main parts:
 Common Language Runtime (CLR)
 Unified Programming Classes
 ASP .NET
 Common Language Runtime
The Common Language Runtime or CLR provides a run-time environment that manages
the execution of .NET Framework applications. The code that targets the CLR is called managed
code. The CLR is the execution engine for the .NET Framework applications and provides a
unified environment across all programming languages. While the component is running, the
runtime is responsible for managing memory allocation, starting up and killing threads and
processes, and enforcing security policy, as well an satisfying any dependencies that the component
might have on other components. At development time, the runtime's role changes slightly;
because it automates so much (for example, memory management), the runtime makes the
developer's experience very simple.
 Unified Programming Classes
The NET Framework provides unified, object oriented, hierarchical, extensible set of class
libraries (APIs). Currently, C++ developers use the Microsoft Foundation Classes; Java developers
use the Windows Foundation Classes, and Visual Basic developers use Visual Basic's APIs. The
.NET Framework unifies these disparate frameworks. By creating a common set of APIs across all
programming languages, the .NET Framework enables cross-language inheritance, error handling,
and debugging. All programming languages, from JScript to C++, become equal and developers
are tree to choose the language that they want to use.
 ASP.NET
ASP .NET is built on the .NET Framework's programming classes and provides a Web
application model in the form of a set of controls and infrastructure that make it simple to build
Web applications. Developers are exposed to a set of ASP .NET controls that encapsulate common
HTML user interface elements such as text boxes, drop-down menus, and so on. These controls
actually run on the Web server, however, and simply project their user interface as HTML to a
browser. On the server, the controls expose an object-oriented programming model that brings the
richness of object-oriented programming to the Web developer. ASP .NET also provides
infrastructure services such as session state management and process recycling that further reduces
the amount of code a developer must write and increase application reliability.
Apart from all these, .NET also includes the .NET Enterprise Servers—server software that
will integrate .NET functionality and make it easier to use. The .NET platform is centered on a
Common Language Runtime and a set of libraries, which can be exploited, by a wide variety of
languages, which are able to work together by compiling all to an Intermediate Language (IL).
1.4 FEATURESOF .NET
 .NET is multi-language
With the NET platform, we can use several languages, such as C++, JScript, Visual Basic
.NET and C#, a new language which emerged with .NET.
All these languages are compiled via an intermediate binary code, which is independent of
hardware and operating systems. This language is MSIL: Microsoft Intermediate Language. MSIL
is then executed in the Common Language Runtime (CLR). MSIL is then translated into machine
code by a Just in Time (JIT) compiler.
 Applications are portable
Applications compiled as intermediate code is presented as Portable Executables (PEs).
These (PEs) can be implemented over a vast range of hardware and software architectures: Intel
PCs with Windows 9x, Windows NT4, Windows 2000 or future 64 bit Windows versions, with
PocketPC (e.g. Windows CE), and other operating systems.
 All languages must comply with a common agreement
For a language to be eligible for the range of languages supported by the .NET platform, it
must provide a set of possibilities and constructions listed in an agreement called the Common
Language Specification, or CLS. To add a language to .NET, all that is required is for it to meet the
requirements of the CLS, and a compiler to convert that language into MSIL.
For example, today if you want to create a COM+ object, you generally have the choice
between VB6 and Visual C++. But VB6 does not give access to all possibilities, and for certain
requirements, you are restricted to VC++. With .NET, all languages will offer the same
possibilities and generally offer the same performance levels, which means you can choose
between Visual Basic .NET and C# depending on your programming habits and preferences, and
are no longer restricted by implementation constraints.
1.5 FEATURESOF VISUAL BASIC .NET
Using Visual Basic is the quickest and easiest way to create powerful, full-featured
applications that take advantage of the graphical user interface in Windows. For companies
developing custom applications, Visual Basic .NET reduces development time costs. Its intuitive
interface makes Visual Basic .NET an excellent tool for programmers.
New users benefit from mouse operations and a consistent look and feel, more advanced
users benefit from easy-to-use features, such as drop-down list boxes and multiple windows
applications.
 Simplicity
Visual Basic has always been one among the simplest language for creating any kind of
applications. With Visual Basic you can develop a single user stand-alone application sitting on a
PC or enterprise wide n-tier applications, which are distributed in the Network or Web
applications.
 Consistency
Now Visual Basic .NET standardizes things such as data types and how objects are exposed
and interoperate independent of the architecture and operating system of the machine. This gives
consistency among all the .NET languages where in a Visual Basic user, can access classes,
components and objects from other .NET programming languages without worrying about
language-specific differences such as data types.
 Garbage collection
There is no need to explicitly allocate or de-allocate memory in Visual Basic .NET. Memory
is allocated as needed, both on the stack and the heap, and reclaimed by the garbage collector when
it is no longer needed. The garbage collector basically monitors a program's resources, looks for
unused objects when the available resources reach a certain threshold, and destroys the objects as it
finds them. One big advantage of garbage collection is that the programmer no longer has to worry
the most common type of circular references, where a child object has a reference to a parent
object, and the parent object has a reference to the child object. In reference counting scheme
where a counter is incremented or decremented when the object is referenced or goes out of scope,
circular references prevent either object from being released and destroyed. The garbage collector,
however, finds these circular references and destroys them.
 Object-orientation
Visual Basic .NET is truly an object-oriented language. Visual Basic .NET can hold its own
with any language that is object oriented. It will stand shoulder-to-shoulder with other object
oriented languages. like C++, C#, JAVA, Smalltalk, and Eiffel. The main features of an object-
oriented language are encapsulation, inheritance, and polymorphism. Earlier versions of Visual
Basic incorporated a part of these features but never supported all the features in the true sense.
Now Visual Basic .NET supports all these features and becomes a truly object oriented language in
itself.
 Type-safety
Earlier versions of Visual Basic allowed the implicit conversion of types. A variable of one
type could be converted automatically to another type. Sometimes this feature can lead to
unexpected results in the programs. Now Visual Basic .NET is type safe in the sense there is no
implicit conversion of types and the programmer has to do their own type conversions.
 Free-Threading
Visual Basic .NET supports threading in applications. Free-threading is basically the idea
that an application can do more than one thing at a time. For instance, we might be printing a
document in the background while the user continues to interact with our application. Free-
threading is very important when creating highly scalable server-side components, and it is equally
useful when creating very interactive user interfaces.
 Structured Exception Handling
Visual Basic .NET supports a structured way handling the errors that occur in an
application. This way of exception handling was there in other languages like C++ and JAVA. This
is a block structure consisting of Try, Catch and Finally keywords. Code in the block between Try
and Catch is protected in such a way that if an error occurs, a Catch block will run. After any Catch
block is run, the code in the finally block will run, allowing us to clean up after an error. To provide
backward compatibility the unstructured way of handling errors using On Error Go To statements
are still retained in Visual Basic .NET.
 Web Forms
For many years VB has been widely regarded having an incredibly powerful forms
designer. We just have to double-click on a control to have the code window pop up, so we can
write code for that control's events. Web Forms bring this technology to HTML development. Web
Forms are browser-neutral - all the code runs on the web server - but at the same time they provide
us with drag and drop form design and the ability to double-click a control to bring up a code
window where we can write server-side code.
 Web Services
A Web service is a component that runs on a web server and allows client programs to call
its method over HTTP. Each method on the components appears as a URL and may return data
(perhaps an XML document) and accept parameters. This technology is based on the open SOAP
(Simple Object Access Protocol) specification. This makes it possible for server-side
components to be available tovirtually any client, regardless of language or platform. Visual Basic
.NET makes it easier both to create and publish, consume or use a Web Service.
1.6 ARCHITECTUREOF VISUAL BASIC .NET
The Common Language Runtime provides the infrastructure for execution of code and also
provides other services, which can be used during execution. Some of the features that CLR
provides are:
 Cross-language integration, especially cross-language inheritance.
 Automatic memory management, which manages object lifetime so that reference counting
is unnecessary.
 Self-describing objects, which make using IDL (Interface Definition Language), type
libraries etc. unnecessary.
 The ability to compile once and run on any CPU and operating system that supports the
runtime which makes the application platform independent.
But, before execution the source code has to be compiled by the Visual Basic .NET compiler
into an intermediate pseudo code, which is a CPU independent set of instructions, called
Microsoft Intermediate Language (MSIL), which can be efficiently converted to binary code.
MSIL code is then converted by a .NET Framework Just In Time (JIT) compiler to native
code, which is CPU-specific code that runs on the same machine that the JIT compiler is running on.
Figure 1.1 illustrates the whole process of execution.
Fig. 1.1: Execution of Visual Basic .NET Programs
If security policy requires the code to be type-safe, the IL is checked for type-safety as part of
the JIT compilation process. During execution, the runtime provides services that include automatic
memory management, debugging support, enhanced security, and interoperability.
2.1 INTRODUCTIONTO VISUAL STUDIO.NETIDE
Microsoft Visual Studio .NET provides a complete development environment for building
applications based on the Microsoft .NET Framework, Microsoft's next-generation Web' application
development platform. It is a single shared integrated development environment (IDE) for all the
languages of .NET like Visual Basic .NET, C# and Visual C++. Using Visual Studio .NET,
developers can create secure, scalable applications and Web services faster than ever before and in
the language of their choice.
With Visual Studio.NET Microsoft introduces two new user interfaces - Windows Forms
and Web Forms, for creating desktop applications and Web applications, respectively.
2.2 INTRODUCTION TO WINDOWSAND WEBFORMS
Windows Forms
Windows Forms is a framework for building Windows applications that utilize the Common
Language Runtime. It enables developers building Windows-based applications to take full
advantage of the rich user interface features available in the Microsoft Windows Operating System.
Source Code
(..vb extension)
Visual Basic Complier
(vbc.exe)
MSIL
(.il file)
Just in time complier
(JIT)
Executable
It leverages many new technologies of NET including a common application framework, managed
execution environment, integrated security and object oriented principles. In addition, Windows
Forms offers full support for quickly and easily connecting to Web Services and building rich, data-
aware applications. With this new shared development environment in Visual Studio .NET,
developers will be able to create Windows Forms applications using any of the languages
supporting the .NET platform, including Visual Basic. NET an d C# (a new language introduced by
Microsoft for .NET Framework).
The advantages of using Windows Forms are as follows:
 Simplicity and Power
Windows Forms offers a programming model for developing Windows applications in a
very simple way and has the power and flexibility of the Common Language Runtime.
 Lower Total Cost of Ownership
Windows Forms provides more than just a great way to build rich Windows based
applications. Developers also benefit from easy deployment capabilities and an integrated security
model. Windows Forms takes advantage of the versioning and deployment features of the .NET
platform to offer reduced deployment costs and higher application robustness over time. This
significantly lowers the maintenance costs (cost of ownership) for applications written in Windows
Forms.
With Windows Forms application, there is no need to deploy an application to the end user's
desktop. Instead, a user can invoke the application simply by typing a URL in a browser. The
application will download to the client machine, run in a secure execution environment, and remove
itself upon completion.
 Visual Inheritance
Visual inheritance is one of the key new features available in Windows Forms that will
enhance developer productivity and facilitate code reuse. For example, an organization could define
a standard base form that contains items such as the corporate logo and perhaps a common toolbar.
This form can be used by the developers through inheritance and extended to meet the requirements
of specific applications while promoting a common user interface across the organization.
 Security
Windows Forms takes full advantage of the security features of the CLR (Common
Language Runtime). As discussed in the first chapter, CLR is responsible for compiling .NET
applications to native machine code. The CLR then steps aside and the program executes as native
compiled code. The CLR enables managed code to declare the security they require and the
gathering of evidence used to evaluate whether or not permission is granted. The managed code is
that piece of code that gets executed inside the runtime environment and enjoys the features of CLR.
 Web Services Support
Windows Forms offers full support for quickly and easily connecting to Web Services. In
Web Services, software functionality becomes exposed as a service that is unaffected by what the
consumer of the service is (unless there are security considerations). Web Services allow developers
to build applications by combining local and remote resources for an overall integrated and
distributed solution.
 Powerful Graphics
Windows Forms provide richer image control including support for more image formats.
Developers will be able to easily access high-end graphics features and create richer, more complex
graphical applications that have the performance customers demand.
Web Forms
Web Forms is based on ASP .NET technology that you use to create programmable web
pages. Th3y can present information, using any markup language, to the user in any browser and
use code on the server to implement application logic.
Creating a scalable Web application was extremely complicated, but Web Forms hides most
of the complexity just as Visual Basic 1.0 did for Windows development.
Following are some of the features of Web Forms:
 It can run on any browser and automatically render the correct, browser-compliant HTML
for features such as styles, layout and so on.
 It can be programmed in any Common Language Runtime language, including Visual Basic
.NET and JScript .NET.
 It supports powerful RAD development tools, such as Visual Studio .NET for designing and
programming forms.
 It supports a rich set of controls that allows developers to cleanly encapsulate page logic into
reusable components.
 Web Forms are extensible with user-created and third party controls.
In the rest of the chapter you will learn about Windows Forms and its controls. Web Forms
will be discussed in the later chapters.
Visual Basic Terminology
Using Visual Basic .NET requires an understanding of some common terminology. The
following table lists some key terms used in Visual Basic .NET. Each term will be explained in
detail later during the course.
Term Definition
Design Time
Any time when an application is being developed in the Visual
Basic.NET environment.
Run Time
Any time when an application is running. At run time, the user interacts
with the application.
Forms
Windows that can be customized to serve as the interface for an
application or as dialog boxes used to gather information to the
application.
Controls
Graphical representations of objects, such as buttons, list boxes, which
users manipulate to provide information to the application.
Objects
A general term used to describe all the forms and controls that make up
a program.
Properties The characteristics of an object, such as size, caption, or color.
Methods
The actions that an object can perform or that can be performed on the
object.
Events
Actions recognized by a form or control. Events occur as the user,
operating system or application interacts with the objects of a program.
2.3 VISUAL STUDIO.NET SOLUTIONSAND PROJECTS
Solutions and Projects are two containers provided by Visual Studio .NET to efficiently
manage the items that are required to create an application, such as references, data connections,
folders, and files. A solution container can contain multiple projects and a project container
typically contains multiple items.
A single solution can contain multiple projects. To manage and monitor your projects and
the solution to which they belong, Visual Studio.NET introduces Solution Explorer, which displays
the hierarchical structure of your solutions and the projects they contain. Solution Explorer is
discussed in detail later in the chapter.
 Solutions
A solution is a logical container for the projects and solution items that can be built into an
application in Visual Studio .NET. If a solution does not already exist when you create a new
project, a solution is automatically generated by Visual Studio.NET to contain it.
The solution file has an extension .sin. All projects are contained within a solution and every
project contains a unique project file. The project file is a list of files contained in the project. The
project file has an extension of vbproj. This file is updated every time you save the project.
 Projects
A project consists of separate components that are stored as' individual files. A simple
project might consist of a form or HTML document, source code files etc. A project is like a
container for components and forms.
When you create a Form the form is stored with .vb extension. Infact, all VB.Net code
modules will be stored in a file with .vb extension. A single .vb file can contain several classes and
forms.
When the project is built, usually you will get an executable program (.exe) or dynamic link
library (.dll) files.
2.4 THE VISUAL STUDIO .NET INTERFACE
Before you start creating Visual Basic applications, you need to explore the Visual Studio
.NET environment. This section introduces you to the integrated development environment and the
tools available for designing the user interface of your application.
The following steps show you how to start a new project in Visual Studio .NET:
1. Select Programs → Microsoft Visual Studio .NET → Microsoft Visual Studio .NET from
the Start menu. This will launch Visual Studio .NET and display the Start Page. If you are
running Visual Studio .NET for the first time, you will get to see the Start Page with the My
Profile option selected as shown in the following figure. The Get Started option will be
selected whenever the Start Page is displayed next time onwards.
Fig. 2.1: Visual Studio .NET Start Page
The Start Page provides a central location for setting preferred options, reading product
news, accessing discussions with developers, instant access to articles, events, and obtaining other
information to get up and running with the Visual Studio.NET environment. It also allows
developers to access existing and recent projects and create new projects with the click of a button.
2. You can set your preferences by specifying your language in the My Profile screen. To do
so, select Visual Basic Developer in the Profile list. This will automatically fill in the other
fields with their default values. You can specify what you want Visual Studio .NET to do
when it starts by selecting an option from the At Startup field at the bottom of the page. The
options available in the At Startup field are as follows:
 Show Start Page: The Start Page will be displayed each time you run Visual Studio
.NET.
 Load last loaded Solution: The previous project will be automatically loaded when
you run Visual Studio .NET.
 Show Open Project dialog box: The Open Project dialog box, where you can select
an existing project to open, will be displayed when you run Visual Studio .NET.
 Show New Project dialog box: The New Project dialog box, where you can specify
the name of a new project, will be displayed when you run Visual Studio NET.
 Show empty environment: A new empty solution will be started when you run
Visual Studio .NET and you have to add new or existing projects to the solution.
3. Select New → Project from the File menu to create a new project. This will display the New
Project dialog box as shown in the following figure.
Fig,. 2.2: New Project Dialog Box
4. The left pane of the dialog box shown in the figure above will list the project types that can
be created with Visual Studio .NET. Select Visual Basic Projects in the Project Types pane.
This will display the templates available for Visual Basic projects in the right pane.
Visual Studio .NET provides the following templates for creating Visual Basic projects.
Windows Application
Select this template if you want to create a traditional standalone application with a Windows form-
based user interface.
Class Library
Select this template if you want to create reusable classes or components that can be shared with
other projects. A class is a collection of functions that can be used in other projects apart from the
current one. This project type is considered windowless and will not contain a Windows Form class.
Windows Control Library
Select this template if you want to create custom controls to use in Windows form-based
applications.
ASP .NET Web Application
Select this template if you want to create a programmable ASP.NET application with static or
dynamic Web pages as a user interface. A Web application is an application that resides on a Web
Server and services requests made through a browser.
ASP .NET Web Service
Select this template if you want to create Web Services that can be called by external applications.
A Web service is a program that resides on a Web server and services request like a Web
application but does not return a HTML page. Instead, it returns the result of a calculation or a
database lookup.
Web Control Library
Select this template if you want to create custom controls that can be used in Web Forms pages.
Console Application
Select this template if you want to create a command-line application. A console application has a
very limited user interface.
Windows Service
The core function of a Windows Service is to run an application in the background. A few
things that make them different from a Windows application are that a Windows Service starts
before any user logs on to the system (if it has been set up to start at boot up).
3.1 INTRODUCTIONTO VARIABLES
A variable is used to hold information in any programming language. They are named areas
in the memory that can store values during program execution. A variable has a name and value.
Variable names are associated with the value that it stores. When you use a variable, you really
mean the data it represents.
Examples of variables would be:
name = “Sisubaladhanasekar. J”
age = 25
Here, the variable Name is used to store the value “Sisubaladhanasekar. J”. Similarly, Age is
a variable name that stores the value 25. When a variable contains a text value (know as a String), it
must be enclosed within double-quotes (“”)
The value of the variable is referred to by the name of the variable when you write the code
for your application. For example, the following statement can be used to display the value stored in
the variable Name in a message box:
MsgBox(name)
The above statement will display the value “Sisubaladhanasekar. J” in the message box.
Identifiers
The name of a variable is known as an identifier. Variable names should always be
meaningful. So that it is easy for people to understand what your program does. The conventions
that should be followed while naming variables are given below:
 Identifiers must begin with a letter or an underscore character (_). If an identifier begins with an
underscore, it must contain at least one other valid identifier character to disambiguate it from a
line continuation.
 Identifiers can have alphabets, numbers and underscore character (_).
 Identifiers cannot contain white spaces or embedded periods.
 Identifiers in Visual Basic .Net are not case sensitive. For example, myvar, MYVAR or myVar
refers to a variable name so that they match their declaration.
 Identifiers must not exceed 255 characters
 Identifiers cannot be a Visual Basic Keyword. Table 3.1 lists the Visual Basic Keywords that
cannot be used as identifiers.
Keywords
Keywords are words that have special meaning for Visual Basic.Net. Keywords are reserved
by the language for its own usage and cannot be used as variable or method names. The reserved
keywords in Visual Basic.Net language are:
AddHandler AddressOf AndAlso Alias And Ansi
As Assembly Auto Boolean ByRef Byte
ByVal Call Case Catch CBool CByte
CChar CDate CDec CDbl Char CInt
Class Clng Cobj Const CShort CSng
CStr CType Date Decimal Declare Default
Delegate Dim DirectCast Do Double Each
Else Elself End Enum Erase Error
Event Exit False Finally For Friend
Function Get GetType GoTo Handles If
Implements Imports In Inherits Integer Interface
Is Let Lib Like Long Loop
Me Mod Module Mustlnherit MustOverride MyBase
MyClass Namespace Nev/ Next Not Nothing
NotInheritable NotOverridable Object On Option Optional
Or OrElse Overloads Overridable Overrides ParamArray
Preserve Private Property Protected Public RaiseEvent
Readonly ReDim REM RemoveHandler Resume Return
Select Set Shadows Shared Short Single
Static Step Stop String Structure Sub
SyncLock Then Throv/ To True Try
TypeOf Unicode Until Variant When While
With WithEvents WriteOnly Xor
Table 3.1: Visual Basic .NET keywords
Literals
The value that is assigned to a variable is known as a literal. The following statement can be
used to assign the literal "John" to a variable called "name":
name = "John"
There are different types of literals such as String literals, Numeric literals, Date literals etc.,
which will be discussed later.
Declaring Variables
Declaring a variable informs the compiler about the variables to be used in your program
and the type of data to be stored in each variable. In Visual Basic .NET, variables should be
declared in advance before you use them, as this is the default and recommended mode. This is
because a compiled application has to create a new variable whenever it runs into a variable that has
not been declared. This involves a lot of statements and slows down the application considerably.
Informing the compiler about the variable and their types before they are used helps it to produce
compact, efficient and optimized code. The compiler can set aside the required number of bytes for
the variables to be used in the application. However, Visual Basic also allows the developers to use
variable without declaring it.
Variables can be declared by using the Dim statement followed by the variable name, the As
keyword and the type. For example,
Dim name As String
Dim age As Integer
In the above declarations, String and Integer are data types used to store text and numeric
values respectively.
The above variables can also be declared on the same line as follows:
Dim name As String, age As Integer
In VB .NET, when multiple variables are declared on the same line, if a variable is not
declared with a type explicitly, then its type is that of the next variable with an explicit type
declaration. Thus, we can declare three String variables called name, address and city and two
integer variables called age and phone on the same line as follows:
Dim name, address, city as String, age, phone as Integer
Note: The functionality is new to VB.Net. Previous versions of Visual Basic would have taken
name, address and age to be of variant type as there is no explicit data type mentioned along with
them.
Implicit Declarations
VB.Net also allows the developers to declare variables without specifying their data type. In
such a case, VB.NET implicitly declares the variable as Object type.
For example:
Dim x, y
Dim Var1
Initializing Variables
Variables can be initialized in the same line where they are declared. For example, the
following statement can be used to declare a variable called name and initialize it to "John".
Dim name As String = "John"
The above statement can also be written in multiple lines as follows:
Dim name As String
name = "John"
You can also declare and initialize multiple variables of the same or different types on the
same line as follows:
Dim name = "John", city As String = "London", age As Integer = 21
3.2 TYPESOF VARIABLES
You have seen how to declare variables using Dim statement. The type that follows the
variable name indicates what type of value the variable can hold. For example,
Dim x As Integer
Specifies that the variable x will hold integer values this section describes the different types
of variables supported by VB.NET and what type of value each one can hold.
The different types of variables in VB. NET are identified through reserved words. Each of
these data types map to a Common Language Runtime type. The reserved words used to name the
different data types are simply aliases for the predefined structure types in the System namespace.
For example, the typo integer is an alias of the struct typo Int16 defined in the System namespace.
The following table gives the supported data types in Visual Basic NET, then corresponding
CLR type structure, their storage size and range of value they can hold.
Visual
Basic type
Common
Language Run
time type structure
Storage
Allocation
Value range
Boolean System.Boolean 2 bytes True orFalse.
Visual
Basic type
Common
Language Run
time type structure
Storage
Allocation
Value range
Byte System. Byte 1 byte 0 through 255(unsigned)
Char System.Char 2 bytes 0 through 65535 (unsigned).
Date System.DateTime 8 bytes 000.00 on January 1. 0001 through 11:59:59 PM on December 31,
9999.
Decimal System.Decimal 16 bytes 0 through +/-79228,162,514,264,337.593,543,950,335 with no
decimal point:
Decimal System.Decimal 16 bytes 0 through +/-79,228,162,514,264,337, 593,543,950,335 with no
decimal point;
0 through +/-7.92281625142643375935439 50335 with 28 places to
the right of the decimal; smallest nonzero numberis +/-0.0000
000000000000000000000001 (+/-1E-28).
Double
(double-
precision
floating-
point)
System.Double 8 bytes -1.79769313486231570E+308 through
-4.94065645841246544E-324 for negative values;
4.94065645841246544E-324 through 1.79769313486231570E+308
for positive values.
Integer System.Int32 4 bytes -2,147,483,648 through 2,147,483,647.
Long
(long
integer)
System.Int64 8 bytes -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807.
Object System.Object
(class)
4 bytes Any type can be stored in a variable of type Object.
Short System.Int16 2 bytes -32,768 through 32,767.
Single
(single-
precision
floating-
point)
System.Single 4 bytes -3.4028235E+38 through -1.401298E-45 for negative values;
1.401298E-45 through 3.4028235E+38 for positive values.
String
(variable-
length)
System.String
(class)
Depends on
implementing
platform
0 to approximately 2 billion Unicode characters.
User-
Defined
Type
(structure)
(inherits from
System.ValueType)
Depends on
implementing
platform
Each member ofthe structure has a range determined by its data type
and independent ofthe ranges ofthe othermembers.
The type of data that can be stored in each of the variables listed in the above table are
described below
Boolean
Boolean Variables can have only two values, either True or False. They are internally stored
as integers that take the value 0 for False and any no-zero value for True. These variables are
initialized to False by default.
Use the keywords True and False to assign one of the two states to Boolean variables
For example
Dim flag as Boolean = True
Boolean variables are generally used for testing conditions. When other numeric types are
converted to Boolean values, 0 becomes False and all other values become True. When Boolean
values are converted to other data types, false becomes 0 and true becomes -1.
Byte
The Byte data type is used for storing data in a single byte. It can hold an integer in the
range of 0 to 255. It is frequently used to access binary files, and image and sound files.
The following statement can be used to declare and store a value in a Byte variable.
Dim X as Byte
X = 250
Let us consider the following statements:
Dim X As Byte
Dim Y As Byte
X = 250
Y = 50
X = X + Y
In the above case, the result 300 cannot be stored in X since X is declared as Byte and the
value is greater than the range of Byte. In this case, VB. NET will generate an overflow error.
The Byte data type can be converted to the Short, Integer, Long, Single, Double, or
Decimal data type without encountering any exception even if Option Strict is On.
Char
Variables declared as Char data type are stored as 16-bit (2-byte) numbers ranging in value
from 0 to 65535. Each 2-byte number represents a single Unicode character.
A value can be assigned to a Char variable as shown below:
Dim choice As Char
choice = "A"
However, the above statements will only work if Option Strict is Off. If it is on, it will
disallow the conversion of a String to a Char. To assign a single character to a Char type when
Option Strict is On, you can append the literal type character C to the end of the string as shown in
the following statement:
Option Strict On
Dim choice As Char
choice = "A"
The other literal type characters have been discussed later in this chapter.
If you assign a string with multiple characters to a Char type variable, only the first character
will be stored in the variable. For example, the following statements
Dim msgtxt As Char
msgtxt = “Hello"
MsgBox (msgtxt)
will display the letter 'H' in the message box.
Integer
Integer type variables are used to store numeric values as signed 32-bit (4-byte) integers.
You have to append the literal type character I to a literal to force it to the Integer data type as
shown in the following statement:
Dim inum As Integer = 3276744 I
The Integer data type can be converted to the Long, Single, Double, or Decimal data type
without encountering any exception even it Option Strict is On.
A Byte or Short can be converted to Integer type without any exception even if Option Strict
is On.
Long
Long variables are used to store numeric values as signed 64-bit (8-byte) integers. You have
to append the literal type character L to a literal to force it to the Long data type as Shown in the
following statement:
Dim Lnum As Long = 3276744 L
The Long data type can be converted to the Single, Double, or Decimal data type without
encountering any exception even if Option Strict is On.
A Byte, Short, or Integer type can be converted to Long type without any exception even if
Option Strict is On.
Object
The Object data type is VB .NET'S universal data type, meaning that it can hold data of any
other data type. The disadvantages of using this type to store any data include poor performance and
poor program readability. Therefore, the use of the Object data type is not recommended whenever
it can be avoided.
The Object data type is use to store all types of data ranging from single characters to an
object such as strings, arrays, classes or interlaces. An Object variable always holds a pointer to the
data, never the data itself. A variable that is declared without specifying a data type is automatically
considered to be of the Object type. However, this is possible only if Option Strict is Off. You
cannot declare a variable without a data type- if the Strict option is on. An Object variable can be
declared in the following ways:
Dim objVar As Object
Or
D-Uii objVar ‘If Option Strict is not On
A variable declared its Object is handled by VB .NET according to the current contents of
the variable. If an integer value is. assigned to an Object, VB .NET treats it as an Integer. If a string
value is assigned to an Object, it is treated as a String. The same variable can hold different types of
data in the course of the same program as shown in the following code:
Dim objVar As Objact
objVar = 123
MsgBox(objVar)
objVar = "stg"
MsgBox(objVar)
The variable objVar in the above statement first stores and displays a numeric value and is
then used to store and display a string value. An Object variable can also be used to store dales. A
normal assignment statement can be used to assign an object to another object variable. For
example,
objA = objB
The Nothing value is used to disassociate an object variable from an object. It is used with
objects and indicates that an object variable has not been initialized. Initially, when the code begins
running, all object variables that have not been initialized during declaration are initialized to
Nothing. Nothing means that there is no object currently assigned to the variable. You must set this
value for an Object variable if you want to disassociate it from the object it represents. For example,
the following statement releases the Object variable after storing and displaying an integer value in
it:
Dim objVar As Object
objVar = 124
MsgBox (objVar)
objVar = Nothing
Short
Short variables are used to store numeric values as signed 16-bit (2-byje) integers. You have
to append the literal type character S to a literal to force it to the Short data type as shown in the
following statement:
Dim snum As Short = 32767S
The Short data type can be converted to the Integer, Long, Single, Double, or Decimal data
type without encountering any exception even if Option Strict is On.
A Byte type can be converted to Short type without any exception even if Option Strict is On.
Single
Single variables are used to stored numeric values as signed 32-bit (4-byte) single-precision
floating point numbers. You have to append the literal type character F to a literal to force it to the
Single data type as shown in the following statement:
Dim singnum As Single = 3276. OF
The Single data type can be converted to the Double or Decimal data type without
encountering any exception even if Option Strict is On.
A Byte, Short, Integer, or Long type can be converted to Single type without any exception
even if Option Strict is On.
String
The String data type is used to store text values and can be declared as follows:
Dim myText As String
myText = "Welcome to Efficsys Infotech"
myText = "50050"
myText = “”
The second assignment in the above code stores the digits as characters in the String
variable while the third one creates an empty string.
Note: You can use a sting variable that holds digits such as "50050" in numeric calculations as VB
.NET will perform the necessary conversion as long as Option Strict is Off.
User-Defined Type (Structures)
The user-defined type in VB .NET is implemented as a structure. A structure is a.
concatenation of one or more members of various data types. The structure is treated as a single
unit, although its members can also be accessed individually.
A structure declaration starts with the Structure statement, and ends with the End Structure
statement. The Structure statement supplies the name of the structure, which is also the identifier of
the data type being defined by the structure. Other parts of the code can use this identifier to declare
the data type of variables.
The declarations between the Structure and End Structure statements define the members of
the structure. Every member must be declared using a Dim statement or a statement that specifies
access, such as Public, Private, or Friend. If a Dim statement is used, the access defaults to public.
For example, to create a data type called employee having name, department, designation,
and salary as its members, the following statements will be used:
Structure employee
Dim name As String
Dim department As String
Dim designation As String
Dim salary As Integer
End Structures
The above declaration creates a new data type called employee that can be used in your
applications just as any other base types such as strings or integers.
Note: A structure cannot be declared in a subroutine or function. It must appear outside any
procedure..
The following statement can be used to declare variables of the type employee:
Dim emp1 As employee
To assign a value to this variable, you must assign a value to each member of the structure.
The members of the structure can be accessed by appending a period and the member name to the
variable name. For example, to assign the values to the variable emp1 declared in the above
statement, the following code has to be used:
emp1.name = "John"
emp1.department = "Sales"
emp1.designation = "Executive"
emp1.salary = 8000
You can access the value stored in the structure and display them in the following way:
MsgBox (emp1.name & emp1.department & emp1.designation & emp1.salary)
In fact, VB .NET displays the list of members in the employee structure as soon as you type
the period after the variable name as shown in the following figure. The list will also display some
default members of the Structure object.
Fig. 3.1: Elements of a Structure
Variable Categories
All the variable types that have been discussed in this chapter can be categorized as Value Types
or Reference Types.
 Value Types
A value type variable holds the data within its own memory allocation. With value types, the
variables have their own copy of data and it is no possible that operations on one can affect the
other.
Value types include all numeric data types, Boolean, Char, Date, all structures (even if their
members are reference types) and enumerated data types.
 Reference Types
A reference type contains a pointer to another memory location that holds the data. In case
of reference types it is possible for two variables to refer to the same object, and hence operations on
one variable to affect the object referenced by the other variable.
Reference types in Visual Basic.NET include Strings, all arrays (even if their elements are
value types) and Class types such as Form. You can assign either a reference type or a value type to
a variable of the Object data type. An Object variable always holds a pointer to the data, never the
data itself. However, if you assign a value type to an Object variable, it behaves as if it holds its own
data.
Identifier Type Characters
Apart from specifying a data type in a declaration statement, you can force the data type of a
variable identifier with a type character. The type character must immediately follow the variable
name, with no intervening characters of any kind. The type character is not part of the name of the
element. An element defined with a type character can be referenced without the type character. For
example,
Dim msgtxt$ 'Declares msgtxt as String data type
The data declaration characters that can used to force a variable to be declared as a specific
type are listed in Table 3.3.
Identifier Type Character Data Type Example
% Integer Dim num%
& Long Dim lnum&
@ Decimal Dim dec® = 37.5
! Single Dim snum!
# Double Dim dnum#
$ String Dim msg$ = "Hello"
Table 3.3: Identifier Type Characters
No identifier type characters exist for the Boolean, Byte, Char, Date, Object, or Short data
types, or for any composite data types.
Literal Type Characters
A literal is a textual representation of a particular value stored in a variable. The form of a
literal as it appears in your code usually determines its data type. The compiler treats integral literals
as Integer unless they are large enough to be Long, and it treats non integral literals as Double. In
the following statements, the data type of the literal is not ambiguous:
A = 365 'This literal is of the Integer data type
B = 7.5 'This literal is of the Double data type
C = False 'This literal is of the Boolean data type
Visual Basic supplies a set of literal type characters, which you can use to force a literal to
assume a data type other than the one its form indicates. You do this by appending the character to
the end of the literal. The following table lists the literal type characters provided by VB.NET.
Literal Type Character Data Type Example
S Short A = 347S
1 Integer B = 3471
L Long C = 347L
D Decimal D = 347D
F Single E = 347F
R Double F = 347R
C Char G = "."C
Table 3.4: Literal Type Characters
No literal type characters exist for the Boolean Byte, Date, Object, or String data types, or
for any composite data types.
3.3 CONSTANTSAND ENUMERATIONSCONSTANTS:
Constants are used to hold values that do not change during the execution of a program.
Constants are used in programs for two reasons:
1. Constants do not change value
This is a safety feature. Once a constant has been declared, you cannot change its value in
subsequent statements. This ensures that the value specified in the constant's declaration will take
effect in the entire program.
For example, you need to use the value of pi (3.14159) for doing math calculations
throughout your program. Instead of specifying the value repeatedly in your code, you can define a
constant named pi and store the value 3.14159 in it. You can use the constant name (pi) anywhere in
your code just like a variable. This will ensure consistency, as the value once assigned to pi cannot
be changed later in the code.
2. Constants are processed faster than variables
When the program is running, the valU3S of constants do not have to be looked up. The
compiler substitutes constant names with their values, and the program executes faster.
 Declaring Constants
The syntax for declaring a constant is:
const constantname [As Type] = value
The As Type clause is optional. If it is not given the constant's type is determined by the
value you assign it.
The <constantname> is a valid constant name that follows the same rules as variable names.
The following example declares a constant called pi and uses it to calculate the
circumference of a circle:
Const pi As Double = 3.14159265358979
Dim radius, circumference As Double
radius =10
circumference = 2 * pi * radius
Enumerations
Enumerations are used to declare a distinct type consisting of a set of named constants.
Enumerations enable you to associate constant values with names. For example, you can declare an
enumeration for a set of integer constants associated with the month names, and then use the month
names rather than their integer values in your code.
Enumeration variables are variables declared with an Enum type. The elements of the Enum
type are initialized to constant values within the Enum statement. The assigned values cannot be
modified at run time. Values can include both positive and negative numbers.
The Enum Type
An Enum type has a name, an underlying type, and a set of fields, each representing a
constant. The name must be a valid Visual Basic .NET qualifier. The underlying type must be one
of the integer types — Byte, Short, Long or Integer. Integer is the default.
The syntax for declaring the Enum type is:
Enum name
Membername [= constantexpression]
Membername [= constantexpression]
…
End Enum
By default, the first constant in an enumeration is initialized to 0, and the value of each
successive enumerator is increased by one. For example, the following enumeration, Months,
contains a constant named Jan with the value 0, a constant named Feb with the value 1, a constant
named Mar with the value of 2, and so on.
Enum Months
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
End Enum
Enumerators can have initializers to override the default values. For example, in the above
example we want that Jan should be assigned the value 1, Feb should be assigned 2 and so on. This
can be achieved using the following declaration:
Enum Months
Jan=1
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
End Enum
In the above enumeration, the sequence of elements is forced to start from 1 instead of 0.
Values for an Enum can have both positive and negative values as shown in the following example:
Enum Colors
White = -1
Red = 1
Black =0
Blue = 2
End Enum
Multiple enum members may share the same associated value. In the example below, the
two members of the enum type, White and Black, have the value 0. Red and Blue will also have the
same value, 1, because both their preceding elements have the value 0.
Enum Colors
White
Red
Black = White
Blue
End Enum
The above decimation is the same as the one given below. In this declaration, White is
automatically assigned the value 0, as it is the first element whereas Black has been explicitly
assigned the same value. .
Enum Colors
White
Red
Black = 0
Blue
End Enum
By default, enumerations are of the Integer type. You can explicitly declare them as Integer,
Short, Long, or Byte. To declare an enumeration explicitly, you can use the following syntax:
Enum MyEnum As Byte
Zero
One
Two
End Enum
Let us now consider an example for using the Enum type. We will create an enumerated
data type that stores the constants for the days of the week starting from Monday as the first day.
We will then display the constant values assigned to the first two and the last two days of the week.
1. Create a new Visual Basic.NET windows application.
2. Go to the Code Window, and declare an Enum type inside the class as shown in the code below:
Public Class Forml
Inherits System.Windows.Forms.Form
Enum daysofweek
Mon = 1
Tue
Wed
Thu
Fri
Sat
Sun
End Enum
Note that the value for Monday has been initialized to 1.
3. Add a command button to the form and change the Text property of the button to "Show Values".
Enter the following code in the button's click event handler to display the values of the enum type.
Private Sub Buttonl_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Buttonl.Click
Dim d As daysofweek
MsgBox("Mon: " & d.Mon & " Tue:" & d.Tue & " Sat: " & _
d.Sat & " Sun:" & d.Sun)
End Sub
4. When you run the application, and click on the button labeled Show Values, you will see the
output as shown below.
Fig. 3.2: Enumerations Output
3.4 OPERATORS
Now that you have seen how to create variables, you need to know how to use operators to
make these variables do useful work for you. Operators are given that name because they operate on
the variables associated with them.
Arithmetic operators
The first major class of operators is arithmetic operators. Arithmetic operators enable you to
perform simple arithmetic on one or more variables. The arithmetic operators supported by VB
.NET are listed in the following table:
Operator Symbol
Addition +
Subtraction -
Multiplication *
Division /and
Mod Mod
Assign =
Exponentiation ^
Table 3.6: Arithmetic Operators
All the operators work the same way as in other programming languages.
The + operator can concatenate two strings apart from adding two numbers.
The - operator can be used to indicate the negative value of a numeric expression apart from
giving the difference between two numbers.
The division operator is of two types:
The first operator handles numbers with decimal points. Usually referred to as the floating-
point division operator, it is represented by the / symbol. The floating-point division operator is
designed to divide values with decimal points, but it can also divide numbers without decimals. The
following code divides the variable a by 2 and puts the result into the variable c.
c = a / 2
If the variable a contains 3, the result stored in c would be 1.5.
To divide integer values or perform a division without a decimal point in the result, you can
use integer division. Integer division is performed the same way floating-point division is, but the
operator is different. Instead of using a forward-slash (/), you use a backward slash (). Using the
same numbers as before, if an integer division is performed:
C = a  2
The decimal part will be truncated, and the result will be 1. The integer division turns your
result into an integer by rounding the original values of the operands to integers for calculating the
results.
The Mod operator divides two numbers and returns the integer. For example, the statement will
store the remainder 1 in the variable num after dividing 5 by 2.
num = 5 Mod 2
The ^ operator raises a number to the power of another number. For example, the statement will
store the value 8 in num.
num = 2 ^ 3
Comparison Operators
The comparison operators are used to compare one or more variables, numbers, constants,
or a combination of the three. VB .NET has many different types of comparison operators, and each
type checks for a different comparison condition. These operators are listed in the following table:
Operator Symbol Used to
Equality = Test if a variable, constant, or number is equal to another
Inequality <> Test if a variable, constant, or number is not equal to another
Greater Than > Test if a variable, constant, or number is greater than another
Less Than < Test if a variable, constant, or number is less than another
Less Than
or Equal To
<=
Test if a variable, constant, or number is less than or equal to
another
Grater Than
or equal To
>=
Test if a variable, constant, or number is greater than or equal to
another
Like Like Test if a string matches a given pattern
Is Is Test if two object references refer to the same object
Table 3.7: Comparison Operators
The Like operator allows you to match a string against a given pattern using wildcard
characters, character lists, or character ranges, in any combination. The following table shows the
characters allowed in a pattern and what they match:
Characters in pattern Matches in string
? Any single character
* Zero or more characters
# Any single digit (0-9)
charlist] Any single character in charlist
Icharlist] Any single character not in charlist
Table 3.8: Pattern Characters
The comparison operators are used as a part of any other expression.
Logical Operators
Another category of operators in VB .NET is logical operators. These operators are listed in
the following table:
Operator Used to
Not Perform a logical negation on a Boolean expression
And Perform a logical conjunction on two Baolean expressions
Or Perform a logical disjunction on two Boolean expressions
Xor Perform a logical exclusion on two expressions
AndAlso Perform- short-circuiting logical conjunction on two expressions
OrElse Perform short-circuiting logical disjunction on two expressions
Table 3.9: Logical Operators
Concatenation operators
 The & Operator
The & operator is a string concatenation-operator used to merge two strings. The syntax for
using this operator is:
result = string1 & string2
For example, if one variable holds the string
First__Name = "John"
and the second holds the string
Lasu_Name = "Smith"
to form a complete name, you need to concatenate these two strings using the following statement:
Name = First_Name & Last_Name
 The + operator
This operator can also be used to concatenate two strings apart from adding two numbers.
For example, the statement
MsgBox("3" + "2")
will display 32.
The following rules apply for using the + operator:
If Then
Both expressions are the same numeric
data types (Byte, Short, Integer, Long,
Single, Double or Decimal)
Add
Both Expressions are strings Concatenate
One expression is a numeric data type
and the other is String
If Option Strict is On, a compile error
is generated; if Option Strict is Off,
implicitly convert String to Double
and add
One expression is a numeric data type
and the other is Nothing
If Option Strict is On a compile error
is generated; if Option Strict is Off,
add, with Nothing valued at zero.
One expression is a string and the other
is nothing
If Option Strict is On a compile error
is generated; if Option Strict is Off,
Concatenation, with Nothing=””
Operator Precedence
When an expression consists of several operations, each part is evaluated and resolved in a
predetermined order called operator precedence. For each type of operator-arithmetic, comparison,
and logical - Visual Basic follows an order of precedence.
Visual Basic first attends to the arithmetic operators, followed by the string concatenation
operator, the comparison operators, and the logical operators, as summarized in Table given below.
Order Operation
Arithmetic
1 Exponents (A)
2 Negation (-)
Order Operation
3 Multiplication (*), division (/ and )
4 Modulo arithmetic (Mod)
5 Addition (+), subtraction (-)
6 String concatenation (&)
Comparison
1 Equality (=)
2 Inequality (<>)
3 Less than (<)
4 Greater than (>)
5 Less than or equal to (<=)
6 Greater than or equal to (>=)
7 Object equivalence (is)
Logical
1 Negation (Not)
2 Conjunction (And, AndAlso)
3 Disjunction (or, OrElse)
4 Exclusion (Xor)
Table 3.17: Operator Precedence
When an expression has more than one operation, each part of that expression is evaluated
in this order from left to right across the expression.
3.5 STATEMENTS
A programming language should be capable of handling every situation with a relatively
small set of commands. It should have the capability to examine external conditions and act
accordingly. It should be able to control the flow of the program. The flow-control statements
provided by VB .NET have been discussed in this section.
Conditional Statements
 If … Then
The If Then structure is used to test a specified condition and execute the following
statements if the condition is True. If the condition evaluates to False it continues with the statement
following the If structure. The If structure can have a single-line or multiple-line syntax.
In the single line syntax, the statements to be executed if the condition is true have to be
given on the same line. If there are multiple statements to be executed, they have to be separated by
a colon (:).
If <condition> Then <statement>
Or
If <condition> Then <statement> : <statement> : <statement>
For example,
If x > y Then MsgBox (“x is greater than y")
Or
If x < y Then x = x + 1 : MsgBox("x=" & x)
Multiple statements following the condition can be broken up into multiple lines using the
End If statement as shown below:
If x < y Then
X = X + 1
MsgBox("X=" & x)
End If
 If … Then … Else
This is a variation of the If...Then statement. It tests a specified condition and executes one
block of statements if the condition is True. The statements in the Else block are executed if the
condition is False. The syntax of the If...Then...Else statement is as follows:
If <condition> Then
<Statements to be executed if condition is True>
Else
<Statements to be executed if condition is False>
End If
For example,
If x > y Then
max = x
Else
max = y
End If
Another variation of this statement uses several conditions with the Elseif keyword. You can
have any number of Elseif clauses. The conditions are evaluated from the top and if one of them is
true, the corresponding block of statements is executed.
For Example,
If x > y Then
MsgBox("x is greater")
ElseIf y > x Then
MsgBox("y is greater")
Else
MsgBox("Both are equal")
End If
 Select Case
The Select Case structure compares one expression to different values. The advantage of
using this over If...Then...Else is that it makes code easier to read and maintain. The Select Case
structure evaluates a single expression once at the top of the structure. The result is then compared
to a list of values. If a match is found, the corresponding block of statements is executed. The syntax
of the Select Case statement is as follows:
Select Case <expression>
Case <valuel>
<statementblock>
Case <value2>
<statementblock>
Case Else
<statementblock>
End Select
For example, take a numeric variable called month that stores the month number. The select
case statement is used to check the month number and display the corresponding month name. If the
number is not in the range of 1 to 12, it displays a message "Invalid month".
Select Case month
Case 1
MsgBox("Jan")
Case 2
MsgBox("Feb")
Case 3
MsgBox("Mar")
Case 4
MsgBox(“Apr")
Case 5
MsgBox("May")
Case 6
MsgBox("Jun")
Case 7
MsgBox(“Jul")
Case 8
MsgBox("Aug")
Case 9
MsgBox("Sep")
Case 10
MsgBoxC'Oct")
Case 11
MsgBox("Nov")
Case 12
MsgBox("Dec”)
Case Else
MsgBox("Invalid Month")
End Select
Fig. 2.3: Visual Studio.NET IDE
The main components of the IDE are discussed below:
 Form Designer
The main window displayed by Visual Studio .NET is known as the Form Designer. The
Form Designer allows you to layout the visible interface of your application and write the code for
your application. The gray surface or form is the window of the new application in the design mode
(refer Fig. 2.3). You have to place the various controls you want to display to the user at runtime on
this form. These controls include buttons, labels, textboxes, checkboxes, radio buttons and lists and
can be found on the toolbox on the left of the main window. The toolbox contains an icon for each
control you can place on the form. The toolbox details have been discussed later in this chapter.
You can place a control on the form by double-clicking on the icon for that control. This
will place a new instance of the control with the default size on the form. You have to resize and
position the control on the form with the mouse. Another way to place a control on the form is by
selecting the icon for the control with the mouse, drag it over the form and draw the outline of the
control on the form. This will place a new instance of the control in the area specified by the outline.
 Solution Explorer
Solution Explorer displays an organized list of projects as well as the corresponding files
and directories that are part of the current solution (refer Fig. 2.4). It provides developers with an
intuitive view of all files in a given project, saving time when editing large, complex projects. It
displays a list of the items that exist in your project and allows you to open the items for
modification or perform other management tasks. A toolbar associated with this window offers
commonly used commands for the item you highlight in the list. If the Solution Explorer is not
visible, you can view it by clicking on the Solution Explorer icon appearing in the toolbar (refer Fig.
2.3).
Fig. 2.4: Solution Explorer Window
Only buttons specific to the item selected in the list appear or the Solution Explorer toolbar.
The toolbars associated with a Windows Form are described below:
View Code: Opens the selected file for editing in the Code Editor.
View Designer: Opens the selected file for designing in the Form Designer.
Refresh: Refreshes the state of selected items in the active view of a Web project.
Show All Files: Shows all project items, including those that have been excluded and those
that are normally hidden. The project initially determines which project
items are hidden.
Properties: Displays property user interface as appropriate for the selected item in the
tree view.
 Toolbox
The Toolbox window displays a variety of items for use in Visual Studio NET. The items
available from this window change depending upon which design editor the developer is using.
Items displayed can include Web and Windows based form controls, ActiveX controls, Web
Services, Hypertext Markup Language elements, objects and items from the windows clipboard.
Fig. 2.5: Toolbox Window
The toolbox is organized into different tabs; each containing related components, controls,
or code. You can add your own tabs to the toolbox by right-clicking and choosing the Add Tab
option. The description of the various tabs appearing in the toolbox is given in the following table.
Tab Description
Data Contains components that provide access to data and data sources.
Components
Contains various components such as event log, message queues,
timer etc.
Windows Forms
Contains Windows Form controls and dialog boxes that can be used
with Windows applications.
Clipboard Ring
Contains the last twelve items added to the system Clipboard using
the Cut or Copy commands. These items can then be dragged from
Tab Description
the Clipboard Ring tab and dropped onto the active editing or
design surface.
General
It will only contain the pointer tool initially. Can be used to store
default controls including custom controls and code fragments.
Crystal Reports
XML Schema
Contains the components that can be added to XML Schemas when
the XML Designer is in Schema view.
Dialog Editor
Web Forms
Contains Web server controls and validation controls that can be
used to create Web pages.
HTML Contains controls that correspond to the standard HTML tags.
Note: All the tabs given in the above table do not appear on the toolbox by default. To view all the
tabs on the toolbox, right-click anywhere on the toolbox and enable the Show All Tabs check box.
 Working with code fragments
Visual Studio.NET allows code snippets to be highlighted in the code window and dragged
onto the toolbox for later use. Typically these fragments are stored on the General Tab, though you
can create your own Tab.
To store a code fragment on the General tab, highlight some text in the Code Editor
window, then drag and drop that highlighted text on to the General tab (The Code Editor window
has been discussed later in this chapter). These items can be dragged back into a code window at
any point and the text will be added.
 Properties Window
Properties are attributes of an object, such as its size, caption and color. They define the
state, behavior, and appearance of a form or a control. Most graphical controls contain properties
that can be changed to define their visual appearance, Controls, and forms can also expose
properties that specify how they will interact with the user and the information that they need to
operate at run time.
The properties window contains the property settings for the selected form or control. You
can use the Properties window to view and set the design-time properties for a form, document, or
control. For example, to change the name of a form to MyForm, select the form, locate the Text
property in the Properties window and change it (refer Fig. 2.8). If the Properties window is not
visible, you can right click the form and select Properties from the shortcut menu.
Fig. 2.6: The Properties Window for a Form
 Code Editor Window
Visual Studio.NET contains an editor window called the Code Editor that can be used to
edit either code or text. The Code Editor supports a language-specific service, such as Visual Basic
or Visual C++, that checks for syntax and usage errors. When you enter text without a project, or
when you create or edit a text document, the window may act as a plain text editor.
You can open the Code Editor window in any of the following ways:
1. Double-click on a form or control in the Form Designer window.
2. Select a form or module in the Solution Explorer and click on the View Code button.
3. Right-click on a form or control in the Form Designer window and select View Code from
the shortcut menu displayed.
4. Select Code from the View menu.
The Code Editor contains two drop down lists at the top of the window. The object list
contains a list of all the controls contained in the form and the Procedure list displays all the events
for that control. You can select the object and event to code from these lists or from the Form
designer.
Fig. 2.7: Code Editor Window
 Server Explorer
Server Explorer is a new server-development console for Visual Studio .NET that helps
developers to access and manipulate data links, database connections and system resources on any
server to which they have network access. With Server Explorer, developers connect to servers and
view their resources including message queues, performance counter, services, processes, event logs
and database objects.
In addition, Server explorer enables developers to make data connections to Microsoft SQL
Server or other database. Server Explorer also gives direct access to all available Web Services on a
particular server. Using Server Explorer, developers can view information about the methods that
Web Services have and can instantly set references to the services for use in an application. The
items appearing in the Server Explorer Window are displayed in the following table:
Fig. 2.8: Server Explorer Window
Note: If any of the Windows mentioned above are not visible select View from the Main Menu Bar
and select the Desired Window. Alternatively for Solution Explorer, Properties and Tool box
windows you can select from the Standard Toolbar using Solution Explorer Icon, Toolbox Icon and
Properties Window Icon.
 References
A section called References appears under your project in the Solution Explorer window.
This section shows the references that are made to assemblies and components in your project.
To add a reference to your project, you can either right-click on the References item in the
Solution Explorer or you can select the Project → Add Reference menu option. This will open the
Add Reference dialog box as shown in the following figure.
Fig. 2.9: Add Reference Dialog Box
This dialog allows you to add references to .NET Components, COM Components and
other Projects to your project. Once a reference has been added, it will be listed in the Solution
Explorer under the References entry. To remove a reference, you can simply right-click on the
reference to be removed and then choose the Remove option.
2.5 EVENT DRIVEN PROGRAMMING
All Visual Basic.NET applications are composed of objects and events associated with
them. Such applications are said to be event-driven.
In traditional or "procedural" applications, the application itself determines which portion of
code is to be executed and in what sequence. Execution starts with the first line of code and follows
the coding sequence defined in the application. At times, the control is transferred to other parts of
the program using certain statements and procedures. Applications written in Visual Basic are
event-driven. In an event-driven application, the code does not follow a predetermined path — it
executes different code sections in response to events. Events can be triggered by the user's actions,
by messages from the system or other applications, or even from the application itself. The sequence
of these events determines the order in which the code executes; thus the path differs each time the
program runs.
Events are associated with the objects of an application. They either act on an object or are
triggered by an object.
Objects
In Visual Basic, an application consists of Forms and Controls, Procedures that respond to
Events and other general purpose procedures. Objects in Visual Basic are basically considered as a
combination of code and data, which is treated and controlled as a unit. Command buttons and other
controls on a form are objects. These objects form a major part of a Visual Basic application, which
allows the user to enter the data as well as view the results. Each form in a Visual Basic project is a
separate object.
Controls
Controls are objects that are placed within form objects. Command buttons, list boxes and
scroll bars are examples of controls. Each type of control has its own set of properties, methods and
events suitable for a particular purpose. The toolbox contains the standard controls. Properties of the
control can be set either at design time or at run time.
 Setting the property of a Control at Design Time
The properties are set at a design time by simply clicking on the control to make it the active
control and then changing the settings in the properties window. The properties that are established
at design time are used as initial settings each time the application runs.
Perform the following steps to set the text in a textbox control to “Hello” and make it center-
aligned.
1. Place a textbox control named TextBox1 on the form and selects the control in the Form
Designer window.
2. The Properties Window will display the properties of the selected control. Change the Text
Property of TextBox1 to Hello and the TextAlign property to Center.
Fig. 2.10: Setting property of a Control
 Setting the property of a Control at Design Time
1. To set the property of a control at run time, the following statement can be included in the
code: For example
Textbox1.Text = “Hello”
Calling Methods
Methods are actions that an object can perform. Methods are a part of objects like Properties
and perform the actions you want. It can affect the value of properties. For example, list boxes have
a List property that can be changed with the Clear method to remove all the items from a list or the
Addltem method to add a new item to a list.
Methods can be called in different ways. The syntax used for calling a method depends on
whether the method returns a value and whether that value will be used by your application.
The following syntax can be used to invoke methods that do not return a value, or you do
not want to use the value returned by the method.
Object.Method([arg1, arg2, ...])
The following syntax can be used if the method returns some value that needs to be stored in
a variable. You need to declare a variable of the appropriate data type returned by the method.
Variable = Object.Method([arg1, arg2, ...] )
Handling Events
An event is an action recognized by a form or control. Any action performed by pressing a
key on the keyboard or clicking a mouse for which code can be written is an event procedure that
runs whenever the event occurs.
Events occur as a result of the user actions or program code, or they can be triggered by the
system. Depending on the event the corresponding procedure is executed, but some events
recognized by one object might not be the same as recognized by other objects. The Code Editor
window displays the events associated with a selected object. Some of the events of a Textbox
Control are listed in the following figure.
Fig. 2.11: Events of a Textbox Control
2.6 WRITINGA SIMPLE APPLICATION USINGVB.NET
Let us start with Visual Studio.NET by creating a simple Windows application displaying a
form with a button labeled “Click here”. When you click the button a message “Hello! Welcome to
the Visual Basic World” should be displayed in a message box.
The following steps show you how to create this application:
1. Select Programs → Microsoft Visual Studio .NET → Microsoft Visual Studio .NET
from the Start menu.
2. Click on the New Project button in the Start page or select New → Project from the File
menu. This will display the New Project dialog box as shown in the following figure.
Fig. 2.12: New Project Dialog Box
3. Select Visual Basic Projects in the Project Types pane and select Windows Application
in the Templates pane. Give the name of the project as “HelloWorld”. Accept the default
location or click Browse and select a new directory location. Click on the OK button to
create the project. This will display an empty form in the Form Designer window as shown
in the following figure.
Fig. 2.13: Form Designer
4. Select a Button control from the Toolbox and place it on the form. Set the Name and Text
property of the button in the Properties window as given in the table below (refer Figure
2.14).
Fig. 2.14: Window showing the Text Property of the Button set
5. Double click the Button control to open the Code Editor window. The template for the
procedure will be automatically created. You have to type the highlighted code in the
following procedure.
Private Sub cmdShowMsg_Click (ByVa1 sender As System.Object, ByVa1 e As
System.EventArgs) Handles cmdShowMsg.Click
MsgBox("Hello! Welcome to the Visual Basic World")
End Sub
Note: The MsgBox function used in the above code displays the specified message in a small
window with the OK button. Users can view the message and click on the OK button to
close the message box. The details of this function will be covered later.
6. Save the project by selecting the Save All option in the File menu.
7. To run the project, select Start from the Debug menu or press the F5 function key on the
keyboard. You can also click on the Start button  on the toolbar. The main window of
your application with a button will be displayed as shown in the following figure.
Fig. 2.15: Output of Hello World Application
8. Click on the button labeled “Click Here”. This will display the message box with the text
“Hello! Welcome to the Visual Basic World” as shown in the following figure.
Fig. 2.16: Message Box Output
2.7 INTRODUCTIONTO FORMS
A Form is a representation of any window displayed in an application. It is used to develop
the user interface. Forms have their own properties, events and methods, which are used to control
their appearance and behavior. A default form, Form1 is added to the development environment
when Visual Basic starts. Visual Basic applies a default set of properties to this form and any new
forms that are added to the project. The properties of these forms can be changed for its appearance
and behavior either at design time or at run time. Another feature of a form is the title bar of the
form. The main components of the title bar are shown in Fig. 2.17.
Fig. 2.17: Form Components
Form Properties
The form’s appearance and behavior are determined through its properties; which are set in
the Properties window at Design Time. This chapter focuses on the main properties of the form.
 Form Border Style: This property controls the appearance of the border for the Form. This
property has the following Settings.
Settings Description
0- None The form does not contain any border or border related
elements.
1-FixedSingle Form cannot be resized by dragging the borders. It can
include control-menu box, title bar, Maximize, and
Minimize buttons. Form has a single line border.
2-Fixed3D This setting is used when a three-dimensional border
effect is desired. The form cannot be resized by dragging
the borders. It can include control-menu box, title bar,
Maximize, and Minimize buttons. There is a raised
border relative to the body of the form.
3-Fixed Dialog This setting is used for designing dialog boxes. The form
cannot be resized by dragging the borders. It can include
title bar, Maximize, and Minimize buttons. There is a
recessed border relative to the body of the form.
4-Sizable This is the Default setting and is often used as the main
window. The form is resizable. It can include control-
menu box, title bar, Maximize, and Minimize buttons. It
can be resized using control-menu box, Maximize or
Minimize button on the title bar, or by using the mouse
pointer at any edge.
Settings Description
5-FixedToolWindow This setting is used for tool windows. It displays a non-
sizable window with a Close button and title bar text in a
reduced font size.
6-SizableToolWindow This setting is also used for tool windows. It displays a
sizable window with a Close button and title bar text in a
reduced font size.
 Text: This property specifies the text that appears on the title bar of the form. The Text can be
set either at design time by changing the Text property in the Properties window or at runtime.
 AutoScroll: Set this property to True if you want to attach scroll bars automatically to the form
if it is resized in such a way that not all its controls are visible. The default value is False.
 ControlBox: The control menu is a simple menu that allows the user to restore, move, resize,
minimize, maximize and close a form. This button can be enabled in the form by setting the
form's ControlBox property in the Properties window. It can be set to either True or False.
 MaximizeBox: Set this property to False if you do not want the Maximize/Restore button on the
title bar and Maximize/Restore option in the Control Menu. The default value is True.
 MinimizeBox: Set this property to False if you do not want the Minimize button on the title bar.
The default value is True.
 MaximumSize: Set this property to specify the maximum size of a form. At runtime, the form
cannot be resized larger than the value sot in this property.
 MinimumSize: Set this property to specify the minimum size of a form. At runtime, the form
cannot be resized smaller than the value set in this property.
 WindowState: This property determines how the form is displayed at startup. This property can
be set to any one of the three options given in the following table.
Options Effect
Normal Opens form in the normal state
Minimized Opens form in the minimized state
Maximized Opens form in the maximized state
 Start Position: This property determines the position of the form at startup. The following table
lists the settings you can use for this property.
Settings Description
Center Parent The form is centered within the bounds of its parent form.
Center Screen The form is centered on the current display, and has the dimensions
specified in the form's size.
Manual The location and size of the form will determine its starting
position.
Windows Default Bounds The form is positioned at the Windows default location and has the
bounds determined by Windows default.
Windows Default Location The form is positioned at the Windows default location and has the
dimensions specified in the form's size.
 Top Most: Set this property to True to specify that a form will remain on top of all other forms
in your application. The default value is False.
 Accept Button: This property allows you to specify the default Accept button for your form.
The Accept button is usually labeled OK and, is the one that is automatically activated when
you press Enter, even if the focus is with another control.
 Cancel Button: This property allows you to specify the default Cancel button for your form.
The Cancel button is usually labeled Cancel and is the one that is automatically activated when
you press the Esc key.
You can select the corresponding control for the Accept Button and Cancel Button from a drop-
down list in the Properties window of the form. The drop-down list will contain the names of all
the command buttons on your form. This property can also be set from within your code.
Form Controls
Some of the common controls that can be placed on the form are described below:
Label: A label is a graphical control used to display read-only text that users cannot
directly edit.
Text Box: Textboxes are commonly used for accepting user input at run time. The
contents of a textbox can be changed programmatically
Button: Button controls are generally used to start or stop a process.
Check Box: This control displays a check box and a label for text and is generally used
to set options.
Radio Button: This control displays a button that can be turned on or off and is used
for selecting an option.
Group Box: This control is used to group a set of controls such as radio buttons on a
labeled and non-scrollable frame.
List Box: This control is used to display a list of text or icons.
Combo Box: This control is used to display a drop-down list of items.
Picture Box: This control displays graphical files, such as bitmaps and icons, in a
frame.
Setting the TabOrder
At runtime, pressing the tab key takes you to the next control on the form. The default tab
order of the controls is the same as the order in which the controls were placed on the form. The tab
order of the controls on the form can be changed while designing the form. Each control has a
Tablndex property setting, which is an integer value. When you press the Tab key, the focus is
shifted to the control whose tab index immediately follows the tab index of the current control.
You can specify the tab order of the various controls by setting the Tablndex property of
each control in the Properties window. The tab index of the first control on the form can be set to 0.
Another way of setting the tab order is by using the Tab Order option in the View menu. To set the
tab order using this option, perform the steps given below.
1. Open the form in the Form Designer and add few controls to it.
2. Select the Tab Order option from the View menu. This will display the current tab order on
the corresponding controls.
3. Starting with the first control, click each control in the order in which you want them to
receive the focus. You have to click all the controls in the desired order. It is not possible to
change the order of a few selected controls. Once you set the tab order for all the controls,
the form will be displayed as shown in Fig. 2.18
Fig. 2.18 Setting the Tab Order
4. If the tab order is correct, click on the Tab Order option in the View menu again. This will
display the form in the normal mode.
An Example
Let us modify the Hello World application created earlier and add a label and a textbox to
the form. The label should prompt the user to enter a name and the textbox should accept the name
from the user. The message "Hello <username>! Welcome to the Visual Basic World" should be
displayed when the user clicks on the button where <username> refers to the text entered by the
user in the Textbox. The following steps show you how to create this application.
Note: The Text property of the TextBox control is used to set or retrieve the value displayed in the
textbox.
1. Open the Hello World application created earlier.
2. In the Form Designer Window, select a Textbox and Label Control from the tool box and
place it on the form.
3. Set the Name and Text property of the Textbox and Label control as shown in the table
below.
Control Property Value to be set
Button Name cmdShowMsg
Text Click here
TextBox Name txtUserName
Text To be left blank
Label Name lblUserName
Text Enter your name
TextAlign MiddleCenter
The form should appear in the Form Designer as shown in the figure below:
4. Double Click the button labeled “Click here” to open the Code Editor window. Modify the
code highlighted below in the cmdShowMsg_Click procedure.
Private Sub cmdShowMsg_Click (ByVa1 sender As System.Object, ByVa1 e As
System.EventArgs) Handles cmdShowMsg.Click
MsgBox("Hello " & txtUserName.text & "! Welcome to the Visual Basic
World")
End Sub
Note: The & symbol used in the MsgBox function is the concatenation operator.
5. Run the program by pressing the F5 Key. This will display the main window of the
application. Enter your name in the textbox provided and click on the button labeled “Click
here”. This will display the message box output as shown in the following figure.
Fig. 2.19: Displaying textbox contents in a message
This chapter has introduced you with the windows forms and some of the basic controls like
textboxes and labels. In the next chapter you will learn more about programming concepts in Visual
Basic.NET and creating Windows based applications.

More Related Content

What's hot (20)

Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
Introduction To Dotnet
Introduction To DotnetIntroduction To Dotnet
Introduction To Dotnet
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
C language ppt
C language pptC language ppt
C language ppt
 
4.C#
4.C#4.C#
4.C#
 
Components of .NET Framework
Components of .NET FrameworkComponents of .NET Framework
Components of .NET Framework
 
7.data types in c#
7.data types in c#7.data types in c#
7.data types in c#
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Net framework
Net frameworkNet framework
Net framework
 
Compiler vs interpreter
Compiler vs interpreterCompiler vs interpreter
Compiler vs interpreter
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Introduction to Software Engineering
Introduction to Software EngineeringIntroduction to Software Engineering
Introduction to Software Engineering
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Common language runtime clr
Common language runtime clrCommon language runtime clr
Common language runtime clr
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 

Similar to Vb.net class notes

Difference between .net and asp.net all you need to know
Difference between .net and asp.net  all you need to knowDifference between .net and asp.net  all you need to know
Difference between .net and asp.net all you need to knowsophiaaaddison
 
Microsoft.net architecturte
Microsoft.net architecturteMicrosoft.net architecturte
Microsoft.net architecturteIblesoft
 
.Net framework vs .net core a complete comparison
.Net framework vs .net core  a complete comparison.Net framework vs .net core  a complete comparison
.Net framework vs .net core a complete comparisonKaty Slemon
 
Online advertising management system
Online advertising management systemOnline advertising management system
Online advertising management systemYesu Raj
 
Online advertising management system
Online advertising management systemOnline advertising management system
Online advertising management systemYesu Raj
 
Pengantar Pemrograman Visual II
Pengantar Pemrograman Visual IIPengantar Pemrograman Visual II
Pengantar Pemrograman Visual IIWahyu Primadi
 
1-.NET Introduction.pptx
1-.NET Introduction.pptx1-.NET Introduction.pptx
1-.NET Introduction.pptxRKAggarwal6
 
Automatic answer checker
Automatic answer checkerAutomatic answer checker
Automatic answer checkerYesu Raj
 
Asp Net Vs Vue JS Which One You Should Choose for Development.pdf
Asp Net Vs Vue JS Which One You Should Choose for Development.pdfAsp Net Vs Vue JS Which One You Should Choose for Development.pdf
Asp Net Vs Vue JS Which One You Should Choose for Development.pdfIntegrated IT Solutions
 
Built Cross-Platform Application with .NET Core Development.pdf
Built Cross-Platform Application with .NET Core Development.pdfBuilt Cross-Platform Application with .NET Core Development.pdf
Built Cross-Platform Application with .NET Core Development.pdfI-Verve Inc
 
.Net Technologies Lesson 1.pptx
.Net Technologies Lesson 1.pptx.Net Technologies Lesson 1.pptx
.Net Technologies Lesson 1.pptxEllenGracePorras
 
What is the next generation of .Net?
What is the next generation of  .Net?What is the next generation of  .Net?
What is the next generation of .Net?Faiyneen Shaikh
 
Top 11 Front-End Web Development Tools To Consider in 2020
 Top 11 Front-End Web Development Tools To Consider in 2020 Top 11 Front-End Web Development Tools To Consider in 2020
Top 11 Front-End Web Development Tools To Consider in 2020Katy Slemon
 
Online furniture management system
Online furniture management systemOnline furniture management system
Online furniture management systemYesu Raj
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.netJaya Kumari
 
Net Framework vs .Net Core A Complete Comparison.pdf
Net Framework vs  .Net Core  A Complete Comparison.pdfNet Framework vs  .Net Core  A Complete Comparison.pdf
Net Framework vs .Net Core A Complete Comparison.pdfWPWeb Infotech
 
Asp.net Web Development.pdf
Asp.net Web Development.pdfAsp.net Web Development.pdf
Asp.net Web Development.pdfSonia Simi
 

Similar to Vb.net class notes (20)

Difference between .net and asp.net all you need to know
Difference between .net and asp.net  all you need to knowDifference between .net and asp.net  all you need to know
Difference between .net and asp.net all you need to know
 
Microsoft.net architecturte
Microsoft.net architecturteMicrosoft.net architecturte
Microsoft.net architecturte
 
.Net framework vs .net core a complete comparison
.Net framework vs .net core  a complete comparison.Net framework vs .net core  a complete comparison
.Net framework vs .net core a complete comparison
 
Online advertising management system
Online advertising management systemOnline advertising management system
Online advertising management system
 
Online advertising management system
Online advertising management systemOnline advertising management system
Online advertising management system
 
Pengantar Pemrograman Visual II
Pengantar Pemrograman Visual IIPengantar Pemrograman Visual II
Pengantar Pemrograman Visual II
 
1-.NET Introduction.pptx
1-.NET Introduction.pptx1-.NET Introduction.pptx
1-.NET Introduction.pptx
 
Automatic answer checker
Automatic answer checkerAutomatic answer checker
Automatic answer checker
 
Asp Net Vs Vue JS Which One You Should Choose for Development.pdf
Asp Net Vs Vue JS Which One You Should Choose for Development.pdfAsp Net Vs Vue JS Which One You Should Choose for Development.pdf
Asp Net Vs Vue JS Which One You Should Choose for Development.pdf
 
Asp.net Vs Vue.js.pdf
Asp.net Vs Vue.js.pdfAsp.net Vs Vue.js.pdf
Asp.net Vs Vue.js.pdf
 
Built Cross-Platform Application with .NET Core Development.pdf
Built Cross-Platform Application with .NET Core Development.pdfBuilt Cross-Platform Application with .NET Core Development.pdf
Built Cross-Platform Application with .NET Core Development.pdf
 
Mca 504 dotnet_unit1
Mca 504 dotnet_unit1Mca 504 dotnet_unit1
Mca 504 dotnet_unit1
 
.Net Technologies Lesson 1.pptx
.Net Technologies Lesson 1.pptx.Net Technologies Lesson 1.pptx
.Net Technologies Lesson 1.pptx
 
What is the next generation of .Net?
What is the next generation of  .Net?What is the next generation of  .Net?
What is the next generation of .Net?
 
Top 11 Front-End Web Development Tools To Consider in 2020
 Top 11 Front-End Web Development Tools To Consider in 2020 Top 11 Front-End Web Development Tools To Consider in 2020
Top 11 Front-End Web Development Tools To Consider in 2020
 
dot net
dot netdot net
dot net
 
Online furniture management system
Online furniture management systemOnline furniture management system
Online furniture management system
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.net
 
Net Framework vs .Net Core A Complete Comparison.pdf
Net Framework vs  .Net Core  A Complete Comparison.pdfNet Framework vs  .Net Core  A Complete Comparison.pdf
Net Framework vs .Net Core A Complete Comparison.pdf
 
Asp.net Web Development.pdf
Asp.net Web Development.pdfAsp.net Web Development.pdf
Asp.net Web Development.pdf
 

More from priyadharshini murugan (18)

Vb.net
Vb.netVb.net
Vb.net
 
PHP
PHPPHP
PHP
 
HTML
HTMLHTML
HTML
 
Onine exam 1
Onine exam 1Onine exam 1
Onine exam 1
 
Web based booking a car taxi5
Web based booking a car taxi5Web based booking a car taxi5
Web based booking a car taxi5
 
New 7 world wonders
New 7 world wondersNew 7 world wonders
New 7 world wonders
 
Values of indian culture
Values of indian cultureValues of indian culture
Values of indian culture
 
Unsolved mysteries of world
Unsolved mysteries of worldUnsolved mysteries of world
Unsolved mysteries of world
 
Bluetooth based-smart-sensor-network
Bluetooth based-smart-sensor-networkBluetooth based-smart-sensor-network
Bluetooth based-smart-sensor-network
 
Environment light pollution
Environment light pollutionEnvironment light pollution
Environment light pollution
 
transport layer
transport layertransport layer
transport layer
 
Bit plane coding
Bit plane codingBit plane coding
Bit plane coding
 
Image compression models
Image compression modelsImage compression models
Image compression models
 
Source coding theorem
Source coding theoremSource coding theorem
Source coding theorem
 
Lossless predictive coding in Digital Image Processing
Lossless predictive coding in Digital Image ProcessingLossless predictive coding in Digital Image Processing
Lossless predictive coding in Digital Image Processing
 
general topic for presentation:Devil's Triangle
general topic for presentation:Devil's Trianglegeneral topic for presentation:Devil's Triangle
general topic for presentation:Devil's Triangle
 
Introduction to css & its attributes with syntax
Introduction to css & its attributes with syntaxIntroduction to css & its attributes with syntax
Introduction to css & its attributes with syntax
 
Open Source Technology
Open Source TechnologyOpen Source Technology
Open Source Technology
 

Recently uploaded

Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 

Recently uploaded (20)

Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 

Vb.net class notes

  • 1. 1.1 INTRODUCTION TO VISUAL BASIC What is Visual Basic? Visual Basic is a programming language designed to build applications with graphical user interfaces (GUIs). The "Visual part refers to the method used to create the graphical user interface (GUI). Rather than writing numerous lines of code to describe the appearance and location of interface elements, you simply place pre-built objects on the screen. This part makes Visual Basic a true RAD (Rapid Application Development) tool. The "Basic" part refers to the BASIC (Beginners All-purpose Symbolic Instruction Code) language, a language used by more programmers than any other language in the history of computing. Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions, and keywords, many of which relate directly to the Windows GUI. Beginners can create useful applications by learning just a few of the keywords, yet the power of the language allows professionals to accomplish anything that can be accomplished using any other programming language. Visual Basic supports a number of features that make it an excellent language for quickly creating full-featured solutions. These features include the following:  Data Access Features By using data access features, developers can create databases, front-end applications and scalable server-side components for most database formats, including Microsoft SQL server and other enterprise-level databases.  Internet Capabilities Internet capabilities make it easy to provide access to documents and applications across the Internet, or an Intranet, from with in the application and to create Internet server applications!  RapidApplicationDevelopment (RAD) A RAD system enables programmers to quickly build working programs. RAD systems provide a number of tools to help build graphical user interfaces that would normally take a large development effort. Visual Basic helps in reducing the development time by providing too ls such as drag-and-drop design and code behind forms. What is Visual Basic .NET? Visual Basic .NET has been designed to create next-generation applications for the Microsoft Windows Operating system and the Web. The Visual Basic language is now truly object-oriented. Microsoft team has streamlined the whole language introducing various new features. These new features open new doors for the Visual Basic developer to rapidly develop scalable Web sites. The data tools now inherently support XML data also.
  • 2. With Visual Basic .NET Microsoft has introduced two new interfaces Windows forms and Web forms. These two interfaces are part of Visual Studio .NET, which is the IDE (Integrated Development Environment) tool used for writing, debugging, compiling and executing the Visual Basic applications. These interfaces provide an easy and efficient way for creating any type of application, be it a standalone application running on single user PC or client server application or enterprise n-tier applications or web centric applications. Visual Basic .NET is designed from ground up to allow developers to easily develop and deploy complex Web applications. 1.2 NEED FOR VISUAL BASIC .NET For nearly a decade, the Visual Basic language has been a popular programming language for the Windows platform. It is easy to underestimate the impact that Visual Basic 1.0 had on the Windows market - for the first time, writing windows applications was a simple and relatively painless task, something with which even a novice programmer could easily create a simple application. Similarly with the introduction of Visual Basic 4.0, it became simple to create COM (Component Object Model) applications, which is nothing but Microsoft's specification for creating pluggable objects, which can be reused in other applications. Even though COM applications can be created using other languages like C++, since the language itself is complex many programmers used Visual Basic for creating COM applications which is more simple to program. But with the introduction of Visual Basic 5.0, using Visual Basic for COM programming became more popular as it provided the ability to create ActiveX controls. Visual Basic 6.0 introduced Web classes, windowless controls, data designers, new reporting designers, and the ability to create data sources. Now Microsoft has introduced an advanced new generation of software that will drive the Internet and its purpose is to make information available any time, any place, on any web-enabled device, be it a desktop, laptop, palmtop or a cell phone. The driving force behind this is a shift in recognizing the reality that applications are beginning to migrate from a standalone executable sitting on a user's hard drive to "Web Services”, which is a distributed application delivered by a web server across the Internet. A key part of Microsoft's thrust into this new web services space is the .NET framework. The .NET framework is designed from the ground up to allow developers to easily write and deploy complex web and Windows applications. If Visual Basic is to retain relevance to users and help attract developers to the new Web services platform, it must be a first class supporter of the .NET Framework. But in many cases features needed to support the .NET framework conflict with existing features in the Visual Basic language. Thus, the decision has been made by Microsoft to loose the bonds of backward compatibility and take the language a step forward in the new evolution. The result is Visual Basic .NET. In short, we can say Microsoft has introduced a totally new language in Visual Basic .NET which supports entirely "Microsoft's .NET strategy", which aims in providing a platform for building internet based applications in a faster, efficient and much more reliable manner along with interoperability with other languages providing a multi-language environment. So, now let us briefly discuss the NET framework before we discuss the features of Visual Basic .NET.
  • 3. 1.3 UNDERSTANDINGTHE .NET FRAMEWORK The Microsoft .NET strategy is an effort that tries to make the Internet a true distributed computing platform by providing a framework that enables computers, devices, and services to collaborate. In short we can say Microsoft .NET is Microsoft's strategy for delivering software as a service. Microsoft .NET Platform is Microsoft's new environment for building, deploying and running Web applications and other enterprise applications. .NET is designed from the ground up to work well with the Internet by embracing Internet standards, including supporting Web Services so programs can easily get data from multiple sites and using XML extensively to facilitate data interchange between different computer systems. .NET also makes accessing your data easier, and makes it far easier to write Web applications that will run well on a wide variety of browsers and devices without having to rewrite the application for each one. More over, the .NET runtime supports simplified and reliable installation and upgrades for ease of use and increased reliability. The .NET Runtime's security and versioning features also increase reliability and enable software to be sold as a service rather than a product. The primary objective of .NET is to provide developers with a means to create interoperable applications using "Web Services" from any sort of terminal, be it a PC, mobile phone, and so forth. What is .NET? .NET is a set of common services, which can be used from a number of languages and have the following specialties:  These services are executed in the form of intermediate code that is independent of the underlying architecture.  They operate in a runtime (Common Language Runtime), which manages resources and monitors application execution. The .NET Framework is a multi-language environment for building, deploying, and running Web Services and applications. The Microsoft .NET platform provides .NET infrastructure and tools to build and operate a new generation of services. It consists of three main parts:  Common Language Runtime (CLR)  Unified Programming Classes  ASP .NET  Common Language Runtime The Common Language Runtime or CLR provides a run-time environment that manages the execution of .NET Framework applications. The code that targets the CLR is called managed code. The CLR is the execution engine for the .NET Framework applications and provides a unified environment across all programming languages. While the component is running, the
  • 4. runtime is responsible for managing memory allocation, starting up and killing threads and processes, and enforcing security policy, as well an satisfying any dependencies that the component might have on other components. At development time, the runtime's role changes slightly; because it automates so much (for example, memory management), the runtime makes the developer's experience very simple.  Unified Programming Classes The NET Framework provides unified, object oriented, hierarchical, extensible set of class libraries (APIs). Currently, C++ developers use the Microsoft Foundation Classes; Java developers use the Windows Foundation Classes, and Visual Basic developers use Visual Basic's APIs. The .NET Framework unifies these disparate frameworks. By creating a common set of APIs across all programming languages, the .NET Framework enables cross-language inheritance, error handling, and debugging. All programming languages, from JScript to C++, become equal and developers are tree to choose the language that they want to use.  ASP.NET ASP .NET is built on the .NET Framework's programming classes and provides a Web application model in the form of a set of controls and infrastructure that make it simple to build Web applications. Developers are exposed to a set of ASP .NET controls that encapsulate common HTML user interface elements such as text boxes, drop-down menus, and so on. These controls actually run on the Web server, however, and simply project their user interface as HTML to a browser. On the server, the controls expose an object-oriented programming model that brings the richness of object-oriented programming to the Web developer. ASP .NET also provides infrastructure services such as session state management and process recycling that further reduces the amount of code a developer must write and increase application reliability. Apart from all these, .NET also includes the .NET Enterprise Servers—server software that will integrate .NET functionality and make it easier to use. The .NET platform is centered on a Common Language Runtime and a set of libraries, which can be exploited, by a wide variety of languages, which are able to work together by compiling all to an Intermediate Language (IL). 1.4 FEATURESOF .NET  .NET is multi-language With the NET platform, we can use several languages, such as C++, JScript, Visual Basic .NET and C#, a new language which emerged with .NET. All these languages are compiled via an intermediate binary code, which is independent of hardware and operating systems. This language is MSIL: Microsoft Intermediate Language. MSIL is then executed in the Common Language Runtime (CLR). MSIL is then translated into machine code by a Just in Time (JIT) compiler.
  • 5.  Applications are portable Applications compiled as intermediate code is presented as Portable Executables (PEs). These (PEs) can be implemented over a vast range of hardware and software architectures: Intel PCs with Windows 9x, Windows NT4, Windows 2000 or future 64 bit Windows versions, with PocketPC (e.g. Windows CE), and other operating systems.  All languages must comply with a common agreement For a language to be eligible for the range of languages supported by the .NET platform, it must provide a set of possibilities and constructions listed in an agreement called the Common Language Specification, or CLS. To add a language to .NET, all that is required is for it to meet the requirements of the CLS, and a compiler to convert that language into MSIL. For example, today if you want to create a COM+ object, you generally have the choice between VB6 and Visual C++. But VB6 does not give access to all possibilities, and for certain requirements, you are restricted to VC++. With .NET, all languages will offer the same possibilities and generally offer the same performance levels, which means you can choose between Visual Basic .NET and C# depending on your programming habits and preferences, and are no longer restricted by implementation constraints. 1.5 FEATURESOF VISUAL BASIC .NET Using Visual Basic is the quickest and easiest way to create powerful, full-featured applications that take advantage of the graphical user interface in Windows. For companies developing custom applications, Visual Basic .NET reduces development time costs. Its intuitive interface makes Visual Basic .NET an excellent tool for programmers. New users benefit from mouse operations and a consistent look and feel, more advanced users benefit from easy-to-use features, such as drop-down list boxes and multiple windows applications.  Simplicity Visual Basic has always been one among the simplest language for creating any kind of applications. With Visual Basic you can develop a single user stand-alone application sitting on a PC or enterprise wide n-tier applications, which are distributed in the Network or Web applications.  Consistency Now Visual Basic .NET standardizes things such as data types and how objects are exposed and interoperate independent of the architecture and operating system of the machine. This gives consistency among all the .NET languages where in a Visual Basic user, can access classes, components and objects from other .NET programming languages without worrying about language-specific differences such as data types.
  • 6.  Garbage collection There is no need to explicitly allocate or de-allocate memory in Visual Basic .NET. Memory is allocated as needed, both on the stack and the heap, and reclaimed by the garbage collector when it is no longer needed. The garbage collector basically monitors a program's resources, looks for unused objects when the available resources reach a certain threshold, and destroys the objects as it finds them. One big advantage of garbage collection is that the programmer no longer has to worry the most common type of circular references, where a child object has a reference to a parent object, and the parent object has a reference to the child object. In reference counting scheme where a counter is incremented or decremented when the object is referenced or goes out of scope, circular references prevent either object from being released and destroyed. The garbage collector, however, finds these circular references and destroys them.  Object-orientation Visual Basic .NET is truly an object-oriented language. Visual Basic .NET can hold its own with any language that is object oriented. It will stand shoulder-to-shoulder with other object oriented languages. like C++, C#, JAVA, Smalltalk, and Eiffel. The main features of an object- oriented language are encapsulation, inheritance, and polymorphism. Earlier versions of Visual Basic incorporated a part of these features but never supported all the features in the true sense. Now Visual Basic .NET supports all these features and becomes a truly object oriented language in itself.  Type-safety Earlier versions of Visual Basic allowed the implicit conversion of types. A variable of one type could be converted automatically to another type. Sometimes this feature can lead to unexpected results in the programs. Now Visual Basic .NET is type safe in the sense there is no implicit conversion of types and the programmer has to do their own type conversions.  Free-Threading Visual Basic .NET supports threading in applications. Free-threading is basically the idea that an application can do more than one thing at a time. For instance, we might be printing a document in the background while the user continues to interact with our application. Free- threading is very important when creating highly scalable server-side components, and it is equally useful when creating very interactive user interfaces.  Structured Exception Handling Visual Basic .NET supports a structured way handling the errors that occur in an application. This way of exception handling was there in other languages like C++ and JAVA. This is a block structure consisting of Try, Catch and Finally keywords. Code in the block between Try and Catch is protected in such a way that if an error occurs, a Catch block will run. After any Catch block is run, the code in the finally block will run, allowing us to clean up after an error. To provide backward compatibility the unstructured way of handling errors using On Error Go To statements are still retained in Visual Basic .NET.
  • 7.  Web Forms For many years VB has been widely regarded having an incredibly powerful forms designer. We just have to double-click on a control to have the code window pop up, so we can write code for that control's events. Web Forms bring this technology to HTML development. Web Forms are browser-neutral - all the code runs on the web server - but at the same time they provide us with drag and drop form design and the ability to double-click a control to bring up a code window where we can write server-side code.  Web Services A Web service is a component that runs on a web server and allows client programs to call its method over HTTP. Each method on the components appears as a URL and may return data (perhaps an XML document) and accept parameters. This technology is based on the open SOAP (Simple Object Access Protocol) specification. This makes it possible for server-side components to be available tovirtually any client, regardless of language or platform. Visual Basic .NET makes it easier both to create and publish, consume or use a Web Service. 1.6 ARCHITECTUREOF VISUAL BASIC .NET The Common Language Runtime provides the infrastructure for execution of code and also provides other services, which can be used during execution. Some of the features that CLR provides are:  Cross-language integration, especially cross-language inheritance.  Automatic memory management, which manages object lifetime so that reference counting is unnecessary.  Self-describing objects, which make using IDL (Interface Definition Language), type libraries etc. unnecessary.  The ability to compile once and run on any CPU and operating system that supports the runtime which makes the application platform independent. But, before execution the source code has to be compiled by the Visual Basic .NET compiler into an intermediate pseudo code, which is a CPU independent set of instructions, called Microsoft Intermediate Language (MSIL), which can be efficiently converted to binary code. MSIL code is then converted by a .NET Framework Just In Time (JIT) compiler to native code, which is CPU-specific code that runs on the same machine that the JIT compiler is running on. Figure 1.1 illustrates the whole process of execution.
  • 8. Fig. 1.1: Execution of Visual Basic .NET Programs If security policy requires the code to be type-safe, the IL is checked for type-safety as part of the JIT compilation process. During execution, the runtime provides services that include automatic memory management, debugging support, enhanced security, and interoperability. 2.1 INTRODUCTIONTO VISUAL STUDIO.NETIDE Microsoft Visual Studio .NET provides a complete development environment for building applications based on the Microsoft .NET Framework, Microsoft's next-generation Web' application development platform. It is a single shared integrated development environment (IDE) for all the languages of .NET like Visual Basic .NET, C# and Visual C++. Using Visual Studio .NET, developers can create secure, scalable applications and Web services faster than ever before and in the language of their choice. With Visual Studio.NET Microsoft introduces two new user interfaces - Windows Forms and Web Forms, for creating desktop applications and Web applications, respectively. 2.2 INTRODUCTION TO WINDOWSAND WEBFORMS Windows Forms Windows Forms is a framework for building Windows applications that utilize the Common Language Runtime. It enables developers building Windows-based applications to take full advantage of the rich user interface features available in the Microsoft Windows Operating System. Source Code (..vb extension) Visual Basic Complier (vbc.exe) MSIL (.il file) Just in time complier (JIT) Executable
  • 9. It leverages many new technologies of NET including a common application framework, managed execution environment, integrated security and object oriented principles. In addition, Windows Forms offers full support for quickly and easily connecting to Web Services and building rich, data- aware applications. With this new shared development environment in Visual Studio .NET, developers will be able to create Windows Forms applications using any of the languages supporting the .NET platform, including Visual Basic. NET an d C# (a new language introduced by Microsoft for .NET Framework). The advantages of using Windows Forms are as follows:  Simplicity and Power Windows Forms offers a programming model for developing Windows applications in a very simple way and has the power and flexibility of the Common Language Runtime.  Lower Total Cost of Ownership Windows Forms provides more than just a great way to build rich Windows based applications. Developers also benefit from easy deployment capabilities and an integrated security model. Windows Forms takes advantage of the versioning and deployment features of the .NET platform to offer reduced deployment costs and higher application robustness over time. This significantly lowers the maintenance costs (cost of ownership) for applications written in Windows Forms. With Windows Forms application, there is no need to deploy an application to the end user's desktop. Instead, a user can invoke the application simply by typing a URL in a browser. The application will download to the client machine, run in a secure execution environment, and remove itself upon completion.  Visual Inheritance Visual inheritance is one of the key new features available in Windows Forms that will enhance developer productivity and facilitate code reuse. For example, an organization could define a standard base form that contains items such as the corporate logo and perhaps a common toolbar. This form can be used by the developers through inheritance and extended to meet the requirements of specific applications while promoting a common user interface across the organization.  Security Windows Forms takes full advantage of the security features of the CLR (Common Language Runtime). As discussed in the first chapter, CLR is responsible for compiling .NET applications to native machine code. The CLR then steps aside and the program executes as native compiled code. The CLR enables managed code to declare the security they require and the gathering of evidence used to evaluate whether or not permission is granted. The managed code is that piece of code that gets executed inside the runtime environment and enjoys the features of CLR.
  • 10.  Web Services Support Windows Forms offers full support for quickly and easily connecting to Web Services. In Web Services, software functionality becomes exposed as a service that is unaffected by what the consumer of the service is (unless there are security considerations). Web Services allow developers to build applications by combining local and remote resources for an overall integrated and distributed solution.  Powerful Graphics Windows Forms provide richer image control including support for more image formats. Developers will be able to easily access high-end graphics features and create richer, more complex graphical applications that have the performance customers demand. Web Forms Web Forms is based on ASP .NET technology that you use to create programmable web pages. Th3y can present information, using any markup language, to the user in any browser and use code on the server to implement application logic. Creating a scalable Web application was extremely complicated, but Web Forms hides most of the complexity just as Visual Basic 1.0 did for Windows development. Following are some of the features of Web Forms:  It can run on any browser and automatically render the correct, browser-compliant HTML for features such as styles, layout and so on.  It can be programmed in any Common Language Runtime language, including Visual Basic .NET and JScript .NET.  It supports powerful RAD development tools, such as Visual Studio .NET for designing and programming forms.  It supports a rich set of controls that allows developers to cleanly encapsulate page logic into reusable components.  Web Forms are extensible with user-created and third party controls. In the rest of the chapter you will learn about Windows Forms and its controls. Web Forms will be discussed in the later chapters. Visual Basic Terminology Using Visual Basic .NET requires an understanding of some common terminology. The following table lists some key terms used in Visual Basic .NET. Each term will be explained in detail later during the course.
  • 11. Term Definition Design Time Any time when an application is being developed in the Visual Basic.NET environment. Run Time Any time when an application is running. At run time, the user interacts with the application. Forms Windows that can be customized to serve as the interface for an application or as dialog boxes used to gather information to the application. Controls Graphical representations of objects, such as buttons, list boxes, which users manipulate to provide information to the application. Objects A general term used to describe all the forms and controls that make up a program. Properties The characteristics of an object, such as size, caption, or color. Methods The actions that an object can perform or that can be performed on the object. Events Actions recognized by a form or control. Events occur as the user, operating system or application interacts with the objects of a program. 2.3 VISUAL STUDIO.NET SOLUTIONSAND PROJECTS Solutions and Projects are two containers provided by Visual Studio .NET to efficiently manage the items that are required to create an application, such as references, data connections, folders, and files. A solution container can contain multiple projects and a project container typically contains multiple items. A single solution can contain multiple projects. To manage and monitor your projects and the solution to which they belong, Visual Studio.NET introduces Solution Explorer, which displays the hierarchical structure of your solutions and the projects they contain. Solution Explorer is discussed in detail later in the chapter.  Solutions A solution is a logical container for the projects and solution items that can be built into an application in Visual Studio .NET. If a solution does not already exist when you create a new project, a solution is automatically generated by Visual Studio.NET to contain it. The solution file has an extension .sin. All projects are contained within a solution and every project contains a unique project file. The project file is a list of files contained in the project. The project file has an extension of vbproj. This file is updated every time you save the project.
  • 12.  Projects A project consists of separate components that are stored as' individual files. A simple project might consist of a form or HTML document, source code files etc. A project is like a container for components and forms. When you create a Form the form is stored with .vb extension. Infact, all VB.Net code modules will be stored in a file with .vb extension. A single .vb file can contain several classes and forms. When the project is built, usually you will get an executable program (.exe) or dynamic link library (.dll) files. 2.4 THE VISUAL STUDIO .NET INTERFACE Before you start creating Visual Basic applications, you need to explore the Visual Studio .NET environment. This section introduces you to the integrated development environment and the tools available for designing the user interface of your application. The following steps show you how to start a new project in Visual Studio .NET: 1. Select Programs → Microsoft Visual Studio .NET → Microsoft Visual Studio .NET from the Start menu. This will launch Visual Studio .NET and display the Start Page. If you are running Visual Studio .NET for the first time, you will get to see the Start Page with the My Profile option selected as shown in the following figure. The Get Started option will be selected whenever the Start Page is displayed next time onwards.
  • 13. Fig. 2.1: Visual Studio .NET Start Page The Start Page provides a central location for setting preferred options, reading product news, accessing discussions with developers, instant access to articles, events, and obtaining other information to get up and running with the Visual Studio.NET environment. It also allows developers to access existing and recent projects and create new projects with the click of a button. 2. You can set your preferences by specifying your language in the My Profile screen. To do so, select Visual Basic Developer in the Profile list. This will automatically fill in the other fields with their default values. You can specify what you want Visual Studio .NET to do when it starts by selecting an option from the At Startup field at the bottom of the page. The options available in the At Startup field are as follows:  Show Start Page: The Start Page will be displayed each time you run Visual Studio .NET.  Load last loaded Solution: The previous project will be automatically loaded when you run Visual Studio .NET.  Show Open Project dialog box: The Open Project dialog box, where you can select an existing project to open, will be displayed when you run Visual Studio .NET.
  • 14.  Show New Project dialog box: The New Project dialog box, where you can specify the name of a new project, will be displayed when you run Visual Studio NET.  Show empty environment: A new empty solution will be started when you run Visual Studio .NET and you have to add new or existing projects to the solution. 3. Select New → Project from the File menu to create a new project. This will display the New Project dialog box as shown in the following figure. Fig,. 2.2: New Project Dialog Box 4. The left pane of the dialog box shown in the figure above will list the project types that can be created with Visual Studio .NET. Select Visual Basic Projects in the Project Types pane. This will display the templates available for Visual Basic projects in the right pane. Visual Studio .NET provides the following templates for creating Visual Basic projects. Windows Application Select this template if you want to create a traditional standalone application with a Windows form- based user interface. Class Library Select this template if you want to create reusable classes or components that can be shared with other projects. A class is a collection of functions that can be used in other projects apart from the current one. This project type is considered windowless and will not contain a Windows Form class.
  • 15. Windows Control Library Select this template if you want to create custom controls to use in Windows form-based applications. ASP .NET Web Application Select this template if you want to create a programmable ASP.NET application with static or dynamic Web pages as a user interface. A Web application is an application that resides on a Web Server and services requests made through a browser. ASP .NET Web Service Select this template if you want to create Web Services that can be called by external applications. A Web service is a program that resides on a Web server and services request like a Web application but does not return a HTML page. Instead, it returns the result of a calculation or a database lookup. Web Control Library Select this template if you want to create custom controls that can be used in Web Forms pages. Console Application Select this template if you want to create a command-line application. A console application has a very limited user interface. Windows Service The core function of a Windows Service is to run an application in the background. A few things that make them different from a Windows application are that a Windows Service starts before any user logs on to the system (if it has been set up to start at boot up). 3.1 INTRODUCTIONTO VARIABLES A variable is used to hold information in any programming language. They are named areas in the memory that can store values during program execution. A variable has a name and value. Variable names are associated with the value that it stores. When you use a variable, you really mean the data it represents.
  • 16. Examples of variables would be: name = “Sisubaladhanasekar. J” age = 25 Here, the variable Name is used to store the value “Sisubaladhanasekar. J”. Similarly, Age is a variable name that stores the value 25. When a variable contains a text value (know as a String), it must be enclosed within double-quotes (“”) The value of the variable is referred to by the name of the variable when you write the code for your application. For example, the following statement can be used to display the value stored in the variable Name in a message box: MsgBox(name) The above statement will display the value “Sisubaladhanasekar. J” in the message box. Identifiers The name of a variable is known as an identifier. Variable names should always be meaningful. So that it is easy for people to understand what your program does. The conventions that should be followed while naming variables are given below:  Identifiers must begin with a letter or an underscore character (_). If an identifier begins with an underscore, it must contain at least one other valid identifier character to disambiguate it from a line continuation.  Identifiers can have alphabets, numbers and underscore character (_).  Identifiers cannot contain white spaces or embedded periods.  Identifiers in Visual Basic .Net are not case sensitive. For example, myvar, MYVAR or myVar refers to a variable name so that they match their declaration.  Identifiers must not exceed 255 characters  Identifiers cannot be a Visual Basic Keyword. Table 3.1 lists the Visual Basic Keywords that cannot be used as identifiers. Keywords Keywords are words that have special meaning for Visual Basic.Net. Keywords are reserved by the language for its own usage and cannot be used as variable or method names. The reserved keywords in Visual Basic.Net language are:
  • 17. AddHandler AddressOf AndAlso Alias And Ansi As Assembly Auto Boolean ByRef Byte ByVal Call Case Catch CBool CByte CChar CDate CDec CDbl Char CInt Class Clng Cobj Const CShort CSng CStr CType Date Decimal Declare Default Delegate Dim DirectCast Do Double Each Else Elself End Enum Erase Error Event Exit False Finally For Friend Function Get GetType GoTo Handles If Implements Imports In Inherits Integer Interface Is Let Lib Like Long Loop Me Mod Module Mustlnherit MustOverride MyBase MyClass Namespace Nev/ Next Not Nothing NotInheritable NotOverridable Object On Option Optional Or OrElse Overloads Overridable Overrides ParamArray Preserve Private Property Protected Public RaiseEvent Readonly ReDim REM RemoveHandler Resume Return Select Set Shadows Shared Short Single Static Step Stop String Structure Sub SyncLock Then Throv/ To True Try TypeOf Unicode Until Variant When While With WithEvents WriteOnly Xor Table 3.1: Visual Basic .NET keywords
  • 18. Literals The value that is assigned to a variable is known as a literal. The following statement can be used to assign the literal "John" to a variable called "name": name = "John" There are different types of literals such as String literals, Numeric literals, Date literals etc., which will be discussed later. Declaring Variables Declaring a variable informs the compiler about the variables to be used in your program and the type of data to be stored in each variable. In Visual Basic .NET, variables should be declared in advance before you use them, as this is the default and recommended mode. This is because a compiled application has to create a new variable whenever it runs into a variable that has not been declared. This involves a lot of statements and slows down the application considerably. Informing the compiler about the variable and their types before they are used helps it to produce compact, efficient and optimized code. The compiler can set aside the required number of bytes for the variables to be used in the application. However, Visual Basic also allows the developers to use variable without declaring it. Variables can be declared by using the Dim statement followed by the variable name, the As keyword and the type. For example, Dim name As String Dim age As Integer In the above declarations, String and Integer are data types used to store text and numeric values respectively. The above variables can also be declared on the same line as follows: Dim name As String, age As Integer In VB .NET, when multiple variables are declared on the same line, if a variable is not declared with a type explicitly, then its type is that of the next variable with an explicit type declaration. Thus, we can declare three String variables called name, address and city and two integer variables called age and phone on the same line as follows: Dim name, address, city as String, age, phone as Integer Note: The functionality is new to VB.Net. Previous versions of Visual Basic would have taken name, address and age to be of variant type as there is no explicit data type mentioned along with them. Implicit Declarations
  • 19. VB.Net also allows the developers to declare variables without specifying their data type. In such a case, VB.NET implicitly declares the variable as Object type. For example: Dim x, y Dim Var1 Initializing Variables Variables can be initialized in the same line where they are declared. For example, the following statement can be used to declare a variable called name and initialize it to "John". Dim name As String = "John" The above statement can also be written in multiple lines as follows: Dim name As String name = "John" You can also declare and initialize multiple variables of the same or different types on the same line as follows: Dim name = "John", city As String = "London", age As Integer = 21 3.2 TYPESOF VARIABLES You have seen how to declare variables using Dim statement. The type that follows the variable name indicates what type of value the variable can hold. For example, Dim x As Integer Specifies that the variable x will hold integer values this section describes the different types of variables supported by VB.NET and what type of value each one can hold. The different types of variables in VB. NET are identified through reserved words. Each of these data types map to a Common Language Runtime type. The reserved words used to name the different data types are simply aliases for the predefined structure types in the System namespace. For example, the typo integer is an alias of the struct typo Int16 defined in the System namespace. The following table gives the supported data types in Visual Basic NET, then corresponding CLR type structure, their storage size and range of value they can hold. Visual Basic type Common Language Run time type structure Storage Allocation Value range Boolean System.Boolean 2 bytes True orFalse.
  • 20. Visual Basic type Common Language Run time type structure Storage Allocation Value range Byte System. Byte 1 byte 0 through 255(unsigned) Char System.Char 2 bytes 0 through 65535 (unsigned). Date System.DateTime 8 bytes 000.00 on January 1. 0001 through 11:59:59 PM on December 31, 9999. Decimal System.Decimal 16 bytes 0 through +/-79228,162,514,264,337.593,543,950,335 with no decimal point: Decimal System.Decimal 16 bytes 0 through +/-79,228,162,514,264,337, 593,543,950,335 with no decimal point; 0 through +/-7.92281625142643375935439 50335 with 28 places to the right of the decimal; smallest nonzero numberis +/-0.0000 000000000000000000000001 (+/-1E-28). Double (double- precision floating- point) System.Double 8 bytes -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values; 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. Integer System.Int32 4 bytes -2,147,483,648 through 2,147,483,647. Long (long integer) System.Int64 8 bytes -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807. Object System.Object (class) 4 bytes Any type can be stored in a variable of type Object. Short System.Int16 2 bytes -32,768 through 32,767. Single (single- precision floating- point) System.Single 4 bytes -3.4028235E+38 through -1.401298E-45 for negative values; 1.401298E-45 through 3.4028235E+38 for positive values. String (variable- length) System.String (class) Depends on implementing platform 0 to approximately 2 billion Unicode characters. User- Defined Type (structure) (inherits from System.ValueType) Depends on implementing platform Each member ofthe structure has a range determined by its data type and independent ofthe ranges ofthe othermembers.
  • 21. The type of data that can be stored in each of the variables listed in the above table are described below Boolean Boolean Variables can have only two values, either True or False. They are internally stored as integers that take the value 0 for False and any no-zero value for True. These variables are initialized to False by default. Use the keywords True and False to assign one of the two states to Boolean variables For example Dim flag as Boolean = True Boolean variables are generally used for testing conditions. When other numeric types are converted to Boolean values, 0 becomes False and all other values become True. When Boolean values are converted to other data types, false becomes 0 and true becomes -1. Byte The Byte data type is used for storing data in a single byte. It can hold an integer in the range of 0 to 255. It is frequently used to access binary files, and image and sound files. The following statement can be used to declare and store a value in a Byte variable. Dim X as Byte X = 250 Let us consider the following statements: Dim X As Byte Dim Y As Byte X = 250 Y = 50 X = X + Y In the above case, the result 300 cannot be stored in X since X is declared as Byte and the value is greater than the range of Byte. In this case, VB. NET will generate an overflow error. The Byte data type can be converted to the Short, Integer, Long, Single, Double, or Decimal data type without encountering any exception even if Option Strict is On. Char
  • 22. Variables declared as Char data type are stored as 16-bit (2-byte) numbers ranging in value from 0 to 65535. Each 2-byte number represents a single Unicode character. A value can be assigned to a Char variable as shown below: Dim choice As Char choice = "A" However, the above statements will only work if Option Strict is Off. If it is on, it will disallow the conversion of a String to a Char. To assign a single character to a Char type when Option Strict is On, you can append the literal type character C to the end of the string as shown in the following statement: Option Strict On Dim choice As Char choice = "A" The other literal type characters have been discussed later in this chapter. If you assign a string with multiple characters to a Char type variable, only the first character will be stored in the variable. For example, the following statements Dim msgtxt As Char msgtxt = “Hello" MsgBox (msgtxt) will display the letter 'H' in the message box. Integer Integer type variables are used to store numeric values as signed 32-bit (4-byte) integers. You have to append the literal type character I to a literal to force it to the Integer data type as shown in the following statement: Dim inum As Integer = 3276744 I The Integer data type can be converted to the Long, Single, Double, or Decimal data type without encountering any exception even it Option Strict is On. A Byte or Short can be converted to Integer type without any exception even if Option Strict is On. Long
  • 23. Long variables are used to store numeric values as signed 64-bit (8-byte) integers. You have to append the literal type character L to a literal to force it to the Long data type as Shown in the following statement: Dim Lnum As Long = 3276744 L The Long data type can be converted to the Single, Double, or Decimal data type without encountering any exception even if Option Strict is On. A Byte, Short, or Integer type can be converted to Long type without any exception even if Option Strict is On. Object The Object data type is VB .NET'S universal data type, meaning that it can hold data of any other data type. The disadvantages of using this type to store any data include poor performance and poor program readability. Therefore, the use of the Object data type is not recommended whenever it can be avoided. The Object data type is use to store all types of data ranging from single characters to an object such as strings, arrays, classes or interlaces. An Object variable always holds a pointer to the data, never the data itself. A variable that is declared without specifying a data type is automatically considered to be of the Object type. However, this is possible only if Option Strict is Off. You cannot declare a variable without a data type- if the Strict option is on. An Object variable can be declared in the following ways: Dim objVar As Object Or D-Uii objVar ‘If Option Strict is not On A variable declared its Object is handled by VB .NET according to the current contents of the variable. If an integer value is. assigned to an Object, VB .NET treats it as an Integer. If a string value is assigned to an Object, it is treated as a String. The same variable can hold different types of data in the course of the same program as shown in the following code: Dim objVar As Objact objVar = 123 MsgBox(objVar) objVar = "stg" MsgBox(objVar) The variable objVar in the above statement first stores and displays a numeric value and is then used to store and display a string value. An Object variable can also be used to store dales. A
  • 24. normal assignment statement can be used to assign an object to another object variable. For example, objA = objB The Nothing value is used to disassociate an object variable from an object. It is used with objects and indicates that an object variable has not been initialized. Initially, when the code begins running, all object variables that have not been initialized during declaration are initialized to Nothing. Nothing means that there is no object currently assigned to the variable. You must set this value for an Object variable if you want to disassociate it from the object it represents. For example, the following statement releases the Object variable after storing and displaying an integer value in it: Dim objVar As Object objVar = 124 MsgBox (objVar) objVar = Nothing Short Short variables are used to store numeric values as signed 16-bit (2-byje) integers. You have to append the literal type character S to a literal to force it to the Short data type as shown in the following statement: Dim snum As Short = 32767S The Short data type can be converted to the Integer, Long, Single, Double, or Decimal data type without encountering any exception even if Option Strict is On. A Byte type can be converted to Short type without any exception even if Option Strict is On. Single Single variables are used to stored numeric values as signed 32-bit (4-byte) single-precision floating point numbers. You have to append the literal type character F to a literal to force it to the Single data type as shown in the following statement: Dim singnum As Single = 3276. OF The Single data type can be converted to the Double or Decimal data type without encountering any exception even if Option Strict is On. A Byte, Short, Integer, or Long type can be converted to Single type without any exception even if Option Strict is On. String
  • 25. The String data type is used to store text values and can be declared as follows: Dim myText As String myText = "Welcome to Efficsys Infotech" myText = "50050" myText = “” The second assignment in the above code stores the digits as characters in the String variable while the third one creates an empty string. Note: You can use a sting variable that holds digits such as "50050" in numeric calculations as VB .NET will perform the necessary conversion as long as Option Strict is Off. User-Defined Type (Structures) The user-defined type in VB .NET is implemented as a structure. A structure is a. concatenation of one or more members of various data types. The structure is treated as a single unit, although its members can also be accessed individually. A structure declaration starts with the Structure statement, and ends with the End Structure statement. The Structure statement supplies the name of the structure, which is also the identifier of the data type being defined by the structure. Other parts of the code can use this identifier to declare the data type of variables. The declarations between the Structure and End Structure statements define the members of the structure. Every member must be declared using a Dim statement or a statement that specifies access, such as Public, Private, or Friend. If a Dim statement is used, the access defaults to public. For example, to create a data type called employee having name, department, designation, and salary as its members, the following statements will be used: Structure employee Dim name As String Dim department As String Dim designation As String Dim salary As Integer End Structures The above declaration creates a new data type called employee that can be used in your applications just as any other base types such as strings or integers. Note: A structure cannot be declared in a subroutine or function. It must appear outside any procedure..
  • 26. The following statement can be used to declare variables of the type employee: Dim emp1 As employee To assign a value to this variable, you must assign a value to each member of the structure. The members of the structure can be accessed by appending a period and the member name to the variable name. For example, to assign the values to the variable emp1 declared in the above statement, the following code has to be used: emp1.name = "John" emp1.department = "Sales" emp1.designation = "Executive" emp1.salary = 8000 You can access the value stored in the structure and display them in the following way: MsgBox (emp1.name & emp1.department & emp1.designation & emp1.salary) In fact, VB .NET displays the list of members in the employee structure as soon as you type the period after the variable name as shown in the following figure. The list will also display some default members of the Structure object. Fig. 3.1: Elements of a Structure Variable Categories All the variable types that have been discussed in this chapter can be categorized as Value Types or Reference Types.  Value Types
  • 27. A value type variable holds the data within its own memory allocation. With value types, the variables have their own copy of data and it is no possible that operations on one can affect the other. Value types include all numeric data types, Boolean, Char, Date, all structures (even if their members are reference types) and enumerated data types.  Reference Types A reference type contains a pointer to another memory location that holds the data. In case of reference types it is possible for two variables to refer to the same object, and hence operations on one variable to affect the object referenced by the other variable. Reference types in Visual Basic.NET include Strings, all arrays (even if their elements are value types) and Class types such as Form. You can assign either a reference type or a value type to a variable of the Object data type. An Object variable always holds a pointer to the data, never the data itself. However, if you assign a value type to an Object variable, it behaves as if it holds its own data. Identifier Type Characters Apart from specifying a data type in a declaration statement, you can force the data type of a variable identifier with a type character. The type character must immediately follow the variable name, with no intervening characters of any kind. The type character is not part of the name of the element. An element defined with a type character can be referenced without the type character. For example, Dim msgtxt$ 'Declares msgtxt as String data type The data declaration characters that can used to force a variable to be declared as a specific type are listed in Table 3.3. Identifier Type Character Data Type Example % Integer Dim num% & Long Dim lnum& @ Decimal Dim dec® = 37.5 ! Single Dim snum! # Double Dim dnum# $ String Dim msg$ = "Hello" Table 3.3: Identifier Type Characters
  • 28. No identifier type characters exist for the Boolean, Byte, Char, Date, Object, or Short data types, or for any composite data types. Literal Type Characters A literal is a textual representation of a particular value stored in a variable. The form of a literal as it appears in your code usually determines its data type. The compiler treats integral literals as Integer unless they are large enough to be Long, and it treats non integral literals as Double. In the following statements, the data type of the literal is not ambiguous: A = 365 'This literal is of the Integer data type B = 7.5 'This literal is of the Double data type C = False 'This literal is of the Boolean data type Visual Basic supplies a set of literal type characters, which you can use to force a literal to assume a data type other than the one its form indicates. You do this by appending the character to the end of the literal. The following table lists the literal type characters provided by VB.NET.
  • 29. Literal Type Character Data Type Example S Short A = 347S 1 Integer B = 3471 L Long C = 347L D Decimal D = 347D F Single E = 347F R Double F = 347R C Char G = "."C Table 3.4: Literal Type Characters No literal type characters exist for the Boolean Byte, Date, Object, or String data types, or for any composite data types. 3.3 CONSTANTSAND ENUMERATIONSCONSTANTS: Constants are used to hold values that do not change during the execution of a program. Constants are used in programs for two reasons: 1. Constants do not change value This is a safety feature. Once a constant has been declared, you cannot change its value in subsequent statements. This ensures that the value specified in the constant's declaration will take effect in the entire program. For example, you need to use the value of pi (3.14159) for doing math calculations throughout your program. Instead of specifying the value repeatedly in your code, you can define a constant named pi and store the value 3.14159 in it. You can use the constant name (pi) anywhere in your code just like a variable. This will ensure consistency, as the value once assigned to pi cannot be changed later in the code. 2. Constants are processed faster than variables When the program is running, the valU3S of constants do not have to be looked up. The compiler substitutes constant names with their values, and the program executes faster.  Declaring Constants The syntax for declaring a constant is:
  • 30. const constantname [As Type] = value The As Type clause is optional. If it is not given the constant's type is determined by the value you assign it. The <constantname> is a valid constant name that follows the same rules as variable names. The following example declares a constant called pi and uses it to calculate the circumference of a circle: Const pi As Double = 3.14159265358979 Dim radius, circumference As Double radius =10 circumference = 2 * pi * radius Enumerations Enumerations are used to declare a distinct type consisting of a set of named constants. Enumerations enable you to associate constant values with names. For example, you can declare an enumeration for a set of integer constants associated with the month names, and then use the month names rather than their integer values in your code. Enumeration variables are variables declared with an Enum type. The elements of the Enum type are initialized to constant values within the Enum statement. The assigned values cannot be modified at run time. Values can include both positive and negative numbers. The Enum Type An Enum type has a name, an underlying type, and a set of fields, each representing a constant. The name must be a valid Visual Basic .NET qualifier. The underlying type must be one of the integer types — Byte, Short, Long or Integer. Integer is the default. The syntax for declaring the Enum type is: Enum name Membername [= constantexpression] Membername [= constantexpression] … End Enum By default, the first constant in an enumeration is initialized to 0, and the value of each successive enumerator is increased by one. For example, the following enumeration, Months, contains a constant named Jan with the value 0, a constant named Feb with the value 1, a constant named Mar with the value of 2, and so on.
  • 31. Enum Months Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec End Enum Enumerators can have initializers to override the default values. For example, in the above example we want that Jan should be assigned the value 1, Feb should be assigned 2 and so on. This can be achieved using the following declaration: Enum Months Jan=1 Feb Mar Apr May Jun Jul Aug Sep Oct Nov
  • 32. Dec End Enum In the above enumeration, the sequence of elements is forced to start from 1 instead of 0. Values for an Enum can have both positive and negative values as shown in the following example: Enum Colors White = -1 Red = 1 Black =0 Blue = 2 End Enum Multiple enum members may share the same associated value. In the example below, the two members of the enum type, White and Black, have the value 0. Red and Blue will also have the same value, 1, because both their preceding elements have the value 0. Enum Colors White Red Black = White Blue End Enum The above decimation is the same as the one given below. In this declaration, White is automatically assigned the value 0, as it is the first element whereas Black has been explicitly assigned the same value. . Enum Colors White Red Black = 0 Blue End Enum By default, enumerations are of the Integer type. You can explicitly declare them as Integer, Short, Long, or Byte. To declare an enumeration explicitly, you can use the following syntax:
  • 33. Enum MyEnum As Byte Zero One Two End Enum Let us now consider an example for using the Enum type. We will create an enumerated data type that stores the constants for the days of the week starting from Monday as the first day. We will then display the constant values assigned to the first two and the last two days of the week. 1. Create a new Visual Basic.NET windows application. 2. Go to the Code Window, and declare an Enum type inside the class as shown in the code below: Public Class Forml Inherits System.Windows.Forms.Form Enum daysofweek Mon = 1 Tue Wed Thu Fri Sat Sun End Enum Note that the value for Monday has been initialized to 1. 3. Add a command button to the form and change the Text property of the button to "Show Values". Enter the following code in the button's click event handler to display the values of the enum type. Private Sub Buttonl_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Buttonl.Click Dim d As daysofweek MsgBox("Mon: " & d.Mon & " Tue:" & d.Tue & " Sat: " & _
  • 34. d.Sat & " Sun:" & d.Sun) End Sub 4. When you run the application, and click on the button labeled Show Values, you will see the output as shown below. Fig. 3.2: Enumerations Output 3.4 OPERATORS Now that you have seen how to create variables, you need to know how to use operators to make these variables do useful work for you. Operators are given that name because they operate on the variables associated with them. Arithmetic operators The first major class of operators is arithmetic operators. Arithmetic operators enable you to perform simple arithmetic on one or more variables. The arithmetic operators supported by VB .NET are listed in the following table: Operator Symbol Addition + Subtraction - Multiplication * Division /and Mod Mod
  • 35. Assign = Exponentiation ^ Table 3.6: Arithmetic Operators All the operators work the same way as in other programming languages. The + operator can concatenate two strings apart from adding two numbers. The - operator can be used to indicate the negative value of a numeric expression apart from giving the difference between two numbers. The division operator is of two types: The first operator handles numbers with decimal points. Usually referred to as the floating- point division operator, it is represented by the / symbol. The floating-point division operator is designed to divide values with decimal points, but it can also divide numbers without decimals. The following code divides the variable a by 2 and puts the result into the variable c. c = a / 2 If the variable a contains 3, the result stored in c would be 1.5. To divide integer values or perform a division without a decimal point in the result, you can use integer division. Integer division is performed the same way floating-point division is, but the operator is different. Instead of using a forward-slash (/), you use a backward slash (). Using the same numbers as before, if an integer division is performed: C = a 2 The decimal part will be truncated, and the result will be 1. The integer division turns your result into an integer by rounding the original values of the operands to integers for calculating the results. The Mod operator divides two numbers and returns the integer. For example, the statement will store the remainder 1 in the variable num after dividing 5 by 2. num = 5 Mod 2 The ^ operator raises a number to the power of another number. For example, the statement will store the value 8 in num. num = 2 ^ 3 Comparison Operators
  • 36. The comparison operators are used to compare one or more variables, numbers, constants, or a combination of the three. VB .NET has many different types of comparison operators, and each type checks for a different comparison condition. These operators are listed in the following table: Operator Symbol Used to Equality = Test if a variable, constant, or number is equal to another Inequality <> Test if a variable, constant, or number is not equal to another Greater Than > Test if a variable, constant, or number is greater than another Less Than < Test if a variable, constant, or number is less than another Less Than or Equal To <= Test if a variable, constant, or number is less than or equal to another Grater Than or equal To >= Test if a variable, constant, or number is greater than or equal to another Like Like Test if a string matches a given pattern Is Is Test if two object references refer to the same object Table 3.7: Comparison Operators The Like operator allows you to match a string against a given pattern using wildcard characters, character lists, or character ranges, in any combination. The following table shows the characters allowed in a pattern and what they match: Characters in pattern Matches in string ? Any single character * Zero or more characters # Any single digit (0-9) charlist] Any single character in charlist Icharlist] Any single character not in charlist
  • 37. Table 3.8: Pattern Characters The comparison operators are used as a part of any other expression. Logical Operators Another category of operators in VB .NET is logical operators. These operators are listed in the following table: Operator Used to Not Perform a logical negation on a Boolean expression And Perform a logical conjunction on two Baolean expressions Or Perform a logical disjunction on two Boolean expressions Xor Perform a logical exclusion on two expressions AndAlso Perform- short-circuiting logical conjunction on two expressions OrElse Perform short-circuiting logical disjunction on two expressions Table 3.9: Logical Operators Concatenation operators  The & Operator The & operator is a string concatenation-operator used to merge two strings. The syntax for using this operator is: result = string1 & string2 For example, if one variable holds the string First__Name = "John" and the second holds the string Lasu_Name = "Smith" to form a complete name, you need to concatenate these two strings using the following statement: Name = First_Name & Last_Name  The + operator This operator can also be used to concatenate two strings apart from adding two numbers.
  • 38. For example, the statement MsgBox("3" + "2") will display 32. The following rules apply for using the + operator: If Then Both expressions are the same numeric data types (Byte, Short, Integer, Long, Single, Double or Decimal) Add Both Expressions are strings Concatenate One expression is a numeric data type and the other is String If Option Strict is On, a compile error is generated; if Option Strict is Off, implicitly convert String to Double and add One expression is a numeric data type and the other is Nothing If Option Strict is On a compile error is generated; if Option Strict is Off, add, with Nothing valued at zero. One expression is a string and the other is nothing If Option Strict is On a compile error is generated; if Option Strict is Off, Concatenation, with Nothing=”” Operator Precedence When an expression consists of several operations, each part is evaluated and resolved in a predetermined order called operator precedence. For each type of operator-arithmetic, comparison, and logical - Visual Basic follows an order of precedence. Visual Basic first attends to the arithmetic operators, followed by the string concatenation operator, the comparison operators, and the logical operators, as summarized in Table given below. Order Operation Arithmetic 1 Exponents (A) 2 Negation (-)
  • 39. Order Operation 3 Multiplication (*), division (/ and ) 4 Modulo arithmetic (Mod) 5 Addition (+), subtraction (-) 6 String concatenation (&) Comparison 1 Equality (=) 2 Inequality (<>) 3 Less than (<) 4 Greater than (>) 5 Less than or equal to (<=) 6 Greater than or equal to (>=) 7 Object equivalence (is) Logical 1 Negation (Not) 2 Conjunction (And, AndAlso) 3 Disjunction (or, OrElse) 4 Exclusion (Xor) Table 3.17: Operator Precedence When an expression has more than one operation, each part of that expression is evaluated in this order from left to right across the expression. 3.5 STATEMENTS A programming language should be capable of handling every situation with a relatively small set of commands. It should have the capability to examine external conditions and act accordingly. It should be able to control the flow of the program. The flow-control statements provided by VB .NET have been discussed in this section. Conditional Statements  If … Then
  • 40. The If Then structure is used to test a specified condition and execute the following statements if the condition is True. If the condition evaluates to False it continues with the statement following the If structure. The If structure can have a single-line or multiple-line syntax. In the single line syntax, the statements to be executed if the condition is true have to be given on the same line. If there are multiple statements to be executed, they have to be separated by a colon (:). If <condition> Then <statement> Or If <condition> Then <statement> : <statement> : <statement> For example, If x > y Then MsgBox (“x is greater than y") Or If x < y Then x = x + 1 : MsgBox("x=" & x) Multiple statements following the condition can be broken up into multiple lines using the End If statement as shown below: If x < y Then X = X + 1 MsgBox("X=" & x) End If  If … Then … Else This is a variation of the If...Then statement. It tests a specified condition and executes one block of statements if the condition is True. The statements in the Else block are executed if the condition is False. The syntax of the If...Then...Else statement is as follows: If <condition> Then <Statements to be executed if condition is True> Else <Statements to be executed if condition is False> End If For example,
  • 41. If x > y Then max = x Else max = y End If Another variation of this statement uses several conditions with the Elseif keyword. You can have any number of Elseif clauses. The conditions are evaluated from the top and if one of them is true, the corresponding block of statements is executed. For Example, If x > y Then MsgBox("x is greater") ElseIf y > x Then MsgBox("y is greater") Else MsgBox("Both are equal") End If  Select Case The Select Case structure compares one expression to different values. The advantage of using this over If...Then...Else is that it makes code easier to read and maintain. The Select Case structure evaluates a single expression once at the top of the structure. The result is then compared to a list of values. If a match is found, the corresponding block of statements is executed. The syntax of the Select Case statement is as follows: Select Case <expression> Case <valuel> <statementblock> Case <value2> <statementblock> Case Else <statementblock>
  • 42. End Select For example, take a numeric variable called month that stores the month number. The select case statement is used to check the month number and display the corresponding month name. If the number is not in the range of 1 to 12, it displays a message "Invalid month". Select Case month Case 1 MsgBox("Jan") Case 2 MsgBox("Feb") Case 3 MsgBox("Mar") Case 4 MsgBox(“Apr") Case 5 MsgBox("May") Case 6 MsgBox("Jun") Case 7 MsgBox(“Jul") Case 8 MsgBox("Aug") Case 9 MsgBox("Sep") Case 10 MsgBoxC'Oct") Case 11 MsgBox("Nov") Case 12 MsgBox("Dec”)
  • 43. Case Else MsgBox("Invalid Month") End Select Fig. 2.3: Visual Studio.NET IDE The main components of the IDE are discussed below:  Form Designer The main window displayed by Visual Studio .NET is known as the Form Designer. The Form Designer allows you to layout the visible interface of your application and write the code for your application. The gray surface or form is the window of the new application in the design mode (refer Fig. 2.3). You have to place the various controls you want to display to the user at runtime on this form. These controls include buttons, labels, textboxes, checkboxes, radio buttons and lists and can be found on the toolbox on the left of the main window. The toolbox contains an icon for each control you can place on the form. The toolbox details have been discussed later in this chapter. You can place a control on the form by double-clicking on the icon for that control. This will place a new instance of the control with the default size on the form. You have to resize and position the control on the form with the mouse. Another way to place a control on the form is by selecting the icon for the control with the mouse, drag it over the form and draw the outline of the control on the form. This will place a new instance of the control in the area specified by the outline.  Solution Explorer
  • 44. Solution Explorer displays an organized list of projects as well as the corresponding files and directories that are part of the current solution (refer Fig. 2.4). It provides developers with an intuitive view of all files in a given project, saving time when editing large, complex projects. It displays a list of the items that exist in your project and allows you to open the items for modification or perform other management tasks. A toolbar associated with this window offers commonly used commands for the item you highlight in the list. If the Solution Explorer is not visible, you can view it by clicking on the Solution Explorer icon appearing in the toolbar (refer Fig. 2.3). Fig. 2.4: Solution Explorer Window Only buttons specific to the item selected in the list appear or the Solution Explorer toolbar. The toolbars associated with a Windows Form are described below: View Code: Opens the selected file for editing in the Code Editor. View Designer: Opens the selected file for designing in the Form Designer. Refresh: Refreshes the state of selected items in the active view of a Web project. Show All Files: Shows all project items, including those that have been excluded and those that are normally hidden. The project initially determines which project items are hidden. Properties: Displays property user interface as appropriate for the selected item in the tree view.  Toolbox
  • 45. The Toolbox window displays a variety of items for use in Visual Studio NET. The items available from this window change depending upon which design editor the developer is using. Items displayed can include Web and Windows based form controls, ActiveX controls, Web Services, Hypertext Markup Language elements, objects and items from the windows clipboard. Fig. 2.5: Toolbox Window The toolbox is organized into different tabs; each containing related components, controls, or code. You can add your own tabs to the toolbox by right-clicking and choosing the Add Tab option. The description of the various tabs appearing in the toolbox is given in the following table. Tab Description Data Contains components that provide access to data and data sources. Components Contains various components such as event log, message queues, timer etc. Windows Forms Contains Windows Form controls and dialog boxes that can be used with Windows applications. Clipboard Ring Contains the last twelve items added to the system Clipboard using the Cut or Copy commands. These items can then be dragged from
  • 46. Tab Description the Clipboard Ring tab and dropped onto the active editing or design surface. General It will only contain the pointer tool initially. Can be used to store default controls including custom controls and code fragments. Crystal Reports XML Schema Contains the components that can be added to XML Schemas when the XML Designer is in Schema view. Dialog Editor Web Forms Contains Web server controls and validation controls that can be used to create Web pages. HTML Contains controls that correspond to the standard HTML tags. Note: All the tabs given in the above table do not appear on the toolbox by default. To view all the tabs on the toolbox, right-click anywhere on the toolbox and enable the Show All Tabs check box.  Working with code fragments Visual Studio.NET allows code snippets to be highlighted in the code window and dragged onto the toolbox for later use. Typically these fragments are stored on the General Tab, though you can create your own Tab. To store a code fragment on the General tab, highlight some text in the Code Editor window, then drag and drop that highlighted text on to the General tab (The Code Editor window has been discussed later in this chapter). These items can be dragged back into a code window at any point and the text will be added.  Properties Window Properties are attributes of an object, such as its size, caption and color. They define the state, behavior, and appearance of a form or a control. Most graphical controls contain properties that can be changed to define their visual appearance, Controls, and forms can also expose properties that specify how they will interact with the user and the information that they need to operate at run time. The properties window contains the property settings for the selected form or control. You can use the Properties window to view and set the design-time properties for a form, document, or control. For example, to change the name of a form to MyForm, select the form, locate the Text
  • 47. property in the Properties window and change it (refer Fig. 2.8). If the Properties window is not visible, you can right click the form and select Properties from the shortcut menu. Fig. 2.6: The Properties Window for a Form  Code Editor Window Visual Studio.NET contains an editor window called the Code Editor that can be used to edit either code or text. The Code Editor supports a language-specific service, such as Visual Basic or Visual C++, that checks for syntax and usage errors. When you enter text without a project, or when you create or edit a text document, the window may act as a plain text editor. You can open the Code Editor window in any of the following ways: 1. Double-click on a form or control in the Form Designer window. 2. Select a form or module in the Solution Explorer and click on the View Code button. 3. Right-click on a form or control in the Form Designer window and select View Code from the shortcut menu displayed.
  • 48. 4. Select Code from the View menu. The Code Editor contains two drop down lists at the top of the window. The object list contains a list of all the controls contained in the form and the Procedure list displays all the events for that control. You can select the object and event to code from these lists or from the Form designer. Fig. 2.7: Code Editor Window  Server Explorer Server Explorer is a new server-development console for Visual Studio .NET that helps developers to access and manipulate data links, database connections and system resources on any server to which they have network access. With Server Explorer, developers connect to servers and view their resources including message queues, performance counter, services, processes, event logs and database objects. In addition, Server explorer enables developers to make data connections to Microsoft SQL Server or other database. Server Explorer also gives direct access to all available Web Services on a particular server. Using Server Explorer, developers can view information about the methods that Web Services have and can instantly set references to the services for use in an application. The items appearing in the Server Explorer Window are displayed in the following table:
  • 49. Fig. 2.8: Server Explorer Window Note: If any of the Windows mentioned above are not visible select View from the Main Menu Bar and select the Desired Window. Alternatively for Solution Explorer, Properties and Tool box windows you can select from the Standard Toolbar using Solution Explorer Icon, Toolbox Icon and Properties Window Icon.  References A section called References appears under your project in the Solution Explorer window. This section shows the references that are made to assemblies and components in your project. To add a reference to your project, you can either right-click on the References item in the Solution Explorer or you can select the Project → Add Reference menu option. This will open the Add Reference dialog box as shown in the following figure. Fig. 2.9: Add Reference Dialog Box
  • 50. This dialog allows you to add references to .NET Components, COM Components and other Projects to your project. Once a reference has been added, it will be listed in the Solution Explorer under the References entry. To remove a reference, you can simply right-click on the reference to be removed and then choose the Remove option. 2.5 EVENT DRIVEN PROGRAMMING All Visual Basic.NET applications are composed of objects and events associated with them. Such applications are said to be event-driven. In traditional or "procedural" applications, the application itself determines which portion of code is to be executed and in what sequence. Execution starts with the first line of code and follows the coding sequence defined in the application. At times, the control is transferred to other parts of the program using certain statements and procedures. Applications written in Visual Basic are event-driven. In an event-driven application, the code does not follow a predetermined path — it executes different code sections in response to events. Events can be triggered by the user's actions, by messages from the system or other applications, or even from the application itself. The sequence of these events determines the order in which the code executes; thus the path differs each time the program runs. Events are associated with the objects of an application. They either act on an object or are triggered by an object. Objects In Visual Basic, an application consists of Forms and Controls, Procedures that respond to Events and other general purpose procedures. Objects in Visual Basic are basically considered as a combination of code and data, which is treated and controlled as a unit. Command buttons and other controls on a form are objects. These objects form a major part of a Visual Basic application, which allows the user to enter the data as well as view the results. Each form in a Visual Basic project is a separate object. Controls Controls are objects that are placed within form objects. Command buttons, list boxes and scroll bars are examples of controls. Each type of control has its own set of properties, methods and events suitable for a particular purpose. The toolbox contains the standard controls. Properties of the control can be set either at design time or at run time.  Setting the property of a Control at Design Time The properties are set at a design time by simply clicking on the control to make it the active control and then changing the settings in the properties window. The properties that are established at design time are used as initial settings each time the application runs. Perform the following steps to set the text in a textbox control to “Hello” and make it center- aligned.
  • 51. 1. Place a textbox control named TextBox1 on the form and selects the control in the Form Designer window. 2. The Properties Window will display the properties of the selected control. Change the Text Property of TextBox1 to Hello and the TextAlign property to Center. Fig. 2.10: Setting property of a Control  Setting the property of a Control at Design Time 1. To set the property of a control at run time, the following statement can be included in the code: For example Textbox1.Text = “Hello” Calling Methods Methods are actions that an object can perform. Methods are a part of objects like Properties and perform the actions you want. It can affect the value of properties. For example, list boxes have a List property that can be changed with the Clear method to remove all the items from a list or the Addltem method to add a new item to a list. Methods can be called in different ways. The syntax used for calling a method depends on whether the method returns a value and whether that value will be used by your application. The following syntax can be used to invoke methods that do not return a value, or you do not want to use the value returned by the method.
  • 52. Object.Method([arg1, arg2, ...]) The following syntax can be used if the method returns some value that needs to be stored in a variable. You need to declare a variable of the appropriate data type returned by the method. Variable = Object.Method([arg1, arg2, ...] ) Handling Events An event is an action recognized by a form or control. Any action performed by pressing a key on the keyboard or clicking a mouse for which code can be written is an event procedure that runs whenever the event occurs. Events occur as a result of the user actions or program code, or they can be triggered by the system. Depending on the event the corresponding procedure is executed, but some events recognized by one object might not be the same as recognized by other objects. The Code Editor window displays the events associated with a selected object. Some of the events of a Textbox Control are listed in the following figure. Fig. 2.11: Events of a Textbox Control 2.6 WRITINGA SIMPLE APPLICATION USINGVB.NET Let us start with Visual Studio.NET by creating a simple Windows application displaying a form with a button labeled “Click here”. When you click the button a message “Hello! Welcome to the Visual Basic World” should be displayed in a message box. The following steps show you how to create this application:
  • 53. 1. Select Programs → Microsoft Visual Studio .NET → Microsoft Visual Studio .NET from the Start menu. 2. Click on the New Project button in the Start page or select New → Project from the File menu. This will display the New Project dialog box as shown in the following figure. Fig. 2.12: New Project Dialog Box 3. Select Visual Basic Projects in the Project Types pane and select Windows Application in the Templates pane. Give the name of the project as “HelloWorld”. Accept the default location or click Browse and select a new directory location. Click on the OK button to create the project. This will display an empty form in the Form Designer window as shown in the following figure. Fig. 2.13: Form Designer
  • 54. 4. Select a Button control from the Toolbox and place it on the form. Set the Name and Text property of the button in the Properties window as given in the table below (refer Figure 2.14). Fig. 2.14: Window showing the Text Property of the Button set 5. Double click the Button control to open the Code Editor window. The template for the procedure will be automatically created. You have to type the highlighted code in the following procedure. Private Sub cmdShowMsg_Click (ByVa1 sender As System.Object, ByVa1 e As System.EventArgs) Handles cmdShowMsg.Click MsgBox("Hello! Welcome to the Visual Basic World") End Sub Note: The MsgBox function used in the above code displays the specified message in a small window with the OK button. Users can view the message and click on the OK button to close the message box. The details of this function will be covered later. 6. Save the project by selecting the Save All option in the File menu.
  • 55. 7. To run the project, select Start from the Debug menu or press the F5 function key on the keyboard. You can also click on the Start button  on the toolbar. The main window of your application with a button will be displayed as shown in the following figure. Fig. 2.15: Output of Hello World Application 8. Click on the button labeled “Click Here”. This will display the message box with the text “Hello! Welcome to the Visual Basic World” as shown in the following figure. Fig. 2.16: Message Box Output 2.7 INTRODUCTIONTO FORMS A Form is a representation of any window displayed in an application. It is used to develop the user interface. Forms have their own properties, events and methods, which are used to control their appearance and behavior. A default form, Form1 is added to the development environment when Visual Basic starts. Visual Basic applies a default set of properties to this form and any new forms that are added to the project. The properties of these forms can be changed for its appearance and behavior either at design time or at run time. Another feature of a form is the title bar of the form. The main components of the title bar are shown in Fig. 2.17.
  • 56. Fig. 2.17: Form Components Form Properties The form’s appearance and behavior are determined through its properties; which are set in the Properties window at Design Time. This chapter focuses on the main properties of the form.  Form Border Style: This property controls the appearance of the border for the Form. This property has the following Settings. Settings Description 0- None The form does not contain any border or border related elements. 1-FixedSingle Form cannot be resized by dragging the borders. It can include control-menu box, title bar, Maximize, and Minimize buttons. Form has a single line border. 2-Fixed3D This setting is used when a three-dimensional border effect is desired. The form cannot be resized by dragging the borders. It can include control-menu box, title bar, Maximize, and Minimize buttons. There is a raised border relative to the body of the form. 3-Fixed Dialog This setting is used for designing dialog boxes. The form cannot be resized by dragging the borders. It can include title bar, Maximize, and Minimize buttons. There is a recessed border relative to the body of the form. 4-Sizable This is the Default setting and is often used as the main window. The form is resizable. It can include control- menu box, title bar, Maximize, and Minimize buttons. It can be resized using control-menu box, Maximize or Minimize button on the title bar, or by using the mouse pointer at any edge.
  • 57. Settings Description 5-FixedToolWindow This setting is used for tool windows. It displays a non- sizable window with a Close button and title bar text in a reduced font size. 6-SizableToolWindow This setting is also used for tool windows. It displays a sizable window with a Close button and title bar text in a reduced font size.  Text: This property specifies the text that appears on the title bar of the form. The Text can be set either at design time by changing the Text property in the Properties window or at runtime.  AutoScroll: Set this property to True if you want to attach scroll bars automatically to the form if it is resized in such a way that not all its controls are visible. The default value is False.  ControlBox: The control menu is a simple menu that allows the user to restore, move, resize, minimize, maximize and close a form. This button can be enabled in the form by setting the form's ControlBox property in the Properties window. It can be set to either True or False.  MaximizeBox: Set this property to False if you do not want the Maximize/Restore button on the title bar and Maximize/Restore option in the Control Menu. The default value is True.  MinimizeBox: Set this property to False if you do not want the Minimize button on the title bar. The default value is True.  MaximumSize: Set this property to specify the maximum size of a form. At runtime, the form cannot be resized larger than the value sot in this property.  MinimumSize: Set this property to specify the minimum size of a form. At runtime, the form cannot be resized smaller than the value set in this property.  WindowState: This property determines how the form is displayed at startup. This property can be set to any one of the three options given in the following table. Options Effect Normal Opens form in the normal state Minimized Opens form in the minimized state Maximized Opens form in the maximized state  Start Position: This property determines the position of the form at startup. The following table lists the settings you can use for this property.
  • 58. Settings Description Center Parent The form is centered within the bounds of its parent form. Center Screen The form is centered on the current display, and has the dimensions specified in the form's size. Manual The location and size of the form will determine its starting position. Windows Default Bounds The form is positioned at the Windows default location and has the bounds determined by Windows default. Windows Default Location The form is positioned at the Windows default location and has the dimensions specified in the form's size.  Top Most: Set this property to True to specify that a form will remain on top of all other forms in your application. The default value is False.  Accept Button: This property allows you to specify the default Accept button for your form. The Accept button is usually labeled OK and, is the one that is automatically activated when you press Enter, even if the focus is with another control.  Cancel Button: This property allows you to specify the default Cancel button for your form. The Cancel button is usually labeled Cancel and is the one that is automatically activated when you press the Esc key. You can select the corresponding control for the Accept Button and Cancel Button from a drop- down list in the Properties window of the form. The drop-down list will contain the names of all the command buttons on your form. This property can also be set from within your code. Form Controls Some of the common controls that can be placed on the form are described below: Label: A label is a graphical control used to display read-only text that users cannot directly edit. Text Box: Textboxes are commonly used for accepting user input at run time. The contents of a textbox can be changed programmatically Button: Button controls are generally used to start or stop a process. Check Box: This control displays a check box and a label for text and is generally used to set options.
  • 59. Radio Button: This control displays a button that can be turned on or off and is used for selecting an option. Group Box: This control is used to group a set of controls such as radio buttons on a labeled and non-scrollable frame. List Box: This control is used to display a list of text or icons. Combo Box: This control is used to display a drop-down list of items. Picture Box: This control displays graphical files, such as bitmaps and icons, in a frame. Setting the TabOrder At runtime, pressing the tab key takes you to the next control on the form. The default tab order of the controls is the same as the order in which the controls were placed on the form. The tab order of the controls on the form can be changed while designing the form. Each control has a Tablndex property setting, which is an integer value. When you press the Tab key, the focus is shifted to the control whose tab index immediately follows the tab index of the current control. You can specify the tab order of the various controls by setting the Tablndex property of each control in the Properties window. The tab index of the first control on the form can be set to 0. Another way of setting the tab order is by using the Tab Order option in the View menu. To set the tab order using this option, perform the steps given below. 1. Open the form in the Form Designer and add few controls to it. 2. Select the Tab Order option from the View menu. This will display the current tab order on the corresponding controls. 3. Starting with the first control, click each control in the order in which you want them to receive the focus. You have to click all the controls in the desired order. It is not possible to change the order of a few selected controls. Once you set the tab order for all the controls, the form will be displayed as shown in Fig. 2.18 Fig. 2.18 Setting the Tab Order
  • 60. 4. If the tab order is correct, click on the Tab Order option in the View menu again. This will display the form in the normal mode. An Example Let us modify the Hello World application created earlier and add a label and a textbox to the form. The label should prompt the user to enter a name and the textbox should accept the name from the user. The message "Hello <username>! Welcome to the Visual Basic World" should be displayed when the user clicks on the button where <username> refers to the text entered by the user in the Textbox. The following steps show you how to create this application. Note: The Text property of the TextBox control is used to set or retrieve the value displayed in the textbox. 1. Open the Hello World application created earlier. 2. In the Form Designer Window, select a Textbox and Label Control from the tool box and place it on the form. 3. Set the Name and Text property of the Textbox and Label control as shown in the table below. Control Property Value to be set Button Name cmdShowMsg Text Click here TextBox Name txtUserName Text To be left blank Label Name lblUserName Text Enter your name TextAlign MiddleCenter The form should appear in the Form Designer as shown in the figure below:
  • 61. 4. Double Click the button labeled “Click here” to open the Code Editor window. Modify the code highlighted below in the cmdShowMsg_Click procedure. Private Sub cmdShowMsg_Click (ByVa1 sender As System.Object, ByVa1 e As System.EventArgs) Handles cmdShowMsg.Click MsgBox("Hello " & txtUserName.text & "! Welcome to the Visual Basic World") End Sub Note: The & symbol used in the MsgBox function is the concatenation operator. 5. Run the program by pressing the F5 Key. This will display the main window of the application. Enter your name in the textbox provided and click on the button labeled “Click here”. This will display the message box output as shown in the following figure. Fig. 2.19: Displaying textbox contents in a message
  • 62. This chapter has introduced you with the windows forms and some of the basic controls like textboxes and labels. In the next chapter you will learn more about programming concepts in Visual Basic.NET and creating Windows based applications.