Professional Documents
Culture Documents
Module Contributor(s):
Ms.Rhythm Choudhary (Assistant Professor, BCA) (Coordinator)
Dr. Neetu Narwal (Associate Professor, BCA)
Mr. Harjender Singh (Assistant Professor, BCA)
1
Ms. Kanika Kundu (Assistant Professor, BCA)
Syllabus
UNIT I
Introduction: Introduction to .Net, Two tier and Three tier client server model, .Net
Architecture, Features of .Net, Advantages of .Net, .Net Framework, CLR, CTS, CLS,
Assemblies. Memory management issues – Garbage Collector and collection process,
Exception Handling, Code Access Security. [T1,R2]
[No. of Hrs: 11]
UNIT – II
Introduction to Visual Basic.Net IDE: Creating a project, Types of project in .Net,
Exploring and coding a project, Solution explorer, toolbox, properties window, Output
window, Object Browser. [T1, T2]
VB.Net Programming Language: Similarities and Differences with Visual Basic,
Variables, Comments, Data Types, Working with Data Structures – Arrays, Array
Lists, Enumerations, Constants, Structures; Introduction to procedures, calling
procedures, argument passing mechanisms, scope of variable. Control Flow
Statements – conditional statement, Loops, Nesting of Loops, MsgBox and Input Box.
[T1,R2]
[No. of Hrs: 11]
UNIT-III
GUI Programming: Introduction to Window Applications, Using Form – Common
Controls, Properties, Methods and Events. Interacting with controls - Textbox, Label,
Button, Listbox, Combobox, Checkbox, Picture Box, Radio Button, Panel, scroll bar,
Timer, ListView, TreeView, toolbar, Status Bar. Dialog Controls, Creating and Using
MDI applications, Toolbar, Status Bar, Creating custom controls, Creating Menus.
[T1, T2, R1]
Object Oriented Features: Classes and Objects, Access Specifiers: Private, Public and
Protected, Building Classes, Reusability, Constructors, Inheritance, Overloading,
Overriding, Creating and Using Namespaces. [T2, R1]
[No. of Hrs: 11]
UNIT – IV
Introduction to ADO: ADO vs ADO.Net, ADO.Net data namespaces, ADO.Net
Object Model, Accessing data from Server Explorer, Creating Connection, Command,
Data Adapter, Data Reader and Data Set with OLEDB and SQLDB, Data Binding.
[T1, R1, R2]
Crystal Report : Connection to Database, Table, Queries, Building Report, Modifying
Report, Formatting Fields, Publishing and exporting reports. [T2] 2
[No. of Hrs: 11]
INDEX
Unit I
Topic Page No
Chapter 1: Introduction to .NET
1.1 Introduction 7
Unit II
Chapter 2: Introduction to Visual Basic.Net IDE
2.1 Introduction 41
2.6 Toolbox 47
3.3 Variables 52
3.4 Constants 53
3.5 Comments 55
3.9 Enumerations 62
3.10 Structures 65
3.13 Loops 80
4
UNIT III
Chapter 4: GUI Programming
4.3.1 Properties 94
4.3.2 Methods 94
4.3.3 Events 94
4.5 Textbox 97
UNIT IV
Chapter 6: Introduction to ADO
The .NET is network enabled technology and a general purpose development platform that
allows you to build a variety of applications like windows application, web application,
console application that can run either on command prompt standalone system or network
environment. It has several key features that are attractive to many developers, which
includes automatic memory management, object oriented approach and modern programming
languages etc that make it easier to build highly efficient quality applications.
.NET Core is a set of runtime, library and compiler components that allow you to create
application that run on Windows, macOS and Linux Operating System. These applications
can be installed on any operating system with limited packages. Hence, it provides a
lightweight development model.
The .NET Framework technology supports building and executing the next generation of
applications and XML Web services. The .NET Framework is designed to fulfill the
following objectives:
•To provide a code-execution environment that promotes safe execution of code by providing
code access security.
•To build all communication on industry standards to ensure that code based on the .NET
Framework can integrate with any code.
One of the primary features of any application design is the system architecture. The system
architecture defines how different parts of the application interact with each other, and what
functionality each part is responsible for performing.
When we create an application there are certain functions that are performed by the
application. Based on the type of functionality it is broadly divided it into three categories:
User service, business service and data service.
1. User Service: It performs the interaction with the user, hence provides the Graphic
User Interface (GUI) or Command User Interface (CUI). It represents the
presentation layer of the application. This layer is used for the design purpose where
data is presented to the user or input is accepted from the user. For example,
designing registration form to accept user information or displaying his personal
details.
2. Business Service: It ensures that business rules are applied to the application. It
guarantees the validation aspects of an application, hence checks the data before it is
send to the data service layer. It represents the business layer. In this layer all business
logics are written like validation of data, calculations, data insertion etc. It acts as an
interface between Client layer and Data Access Layer. This layer is also called the
intermediary layer that helps to make communication faster between client and data
layer.
3. Data Service: It comprises of data and functions for manipulating the data. Almost
every application requires data services; data service deals with user data and provides
methods and functionality to maintain the secrecy, validity and authentication of the
data. It represents the data layer of the application. Data Access Layer contains
methods to connect with database and to perform insert, update, delete, select
operations on database.
Each category is implemented as a layer in an application. These three layers form the base of
the models or architecture used in application development. Applications may vary from
single-tier desktop applications to multi-tier applications.
There are three main classes of application architecture. They can be characterized by the
number of layers between the user and the data. Each layer generally runs on a different
system or in a different process space on the same system.
Monolithic Application
Fat Server
Fat Client
Advantages:
1. The application performance will degrade with the increase in number of users.
2. It is cost-ineffective.
3. Placing the business logic on the client system can be risky in terms of security of
data.
The three-tier application model, segments an application's components into three tiers of
services. These tiers do not necessarily correspond to physical locations on various computers
on a network, but rather to logical layers of the application. The user services layer, gives a
user access to the application. This layer presents data to the user and optionally permits data
manipulation and data entry.
10
Figure 1.3 3-Tier Architecture separates User Services, Business Services and Data Service
The business services layer, consists of business and data rules. It is also referred to as the
business logic tier. The components that make up this layer can exist on a server machine, to
assist in resource sharing. These components can be used to enforce business rules, such as
business algorithms and legal or governmental regulations, and data rules.These middle-tier
components are not tied to a specific client, they can be used by all applications and can be
moved to different locations. For example, simple edits can be placed on the client side to
minimize network round-trips, or data rules can be placed in stored procedures. The data
services layer, interacts with persistent data usually stored in a database or in permanent
storage. It can be accessed through the business services layer and on occasion by the user
services layer. This layer consists of data access components to aid in resource sharing and to
allow clients to be configured without installing the DBMS libraries and ODBC drivers on
each client.
During an application's life cycle, the three-tier approach provides benefits such as
reusability, flexibility, manageability, maintainability, and scalability. You can share and
reuse the components and services you create, and you can distribute them across a network
of computers as needed. You can divide large and complex projects into simpler projects and
assign them to different programmers or programming teams.
Note: In a three-tiered application, the client-side application will be thinner than a client-
server application because it will not contain the service components now located in the
middle tier. This results in less overhead for the user, but more network traffic for the system
because components are distributed among different machines.
Advantages:
The .NET Framework is an application development platform that provides services for
building, deploying, and running desktop, phone and web applications and web services. It
consists of the common language runtime (CLR), which provides memory management and
other system services, and an extensive class library, which includes code for major areas of
application development.
The .NET Framework provides the following services for application developers:
Common type system- In traditional programming languages, basic types is defined by the
compiler, which complicates cross-language interoperability. In the .NET Framework, basic
types are defined by the .NET Framework type system and are common to all languages that
target the .NET Framework.
An extensive class library- In traditional programming languages, you need to write code to
handle low-level programming operations. The .NET Framework Class Library provides
programmers with a rich set of library of types and their members. . NET has an expansive
standard set of class libraries, referred to as either the base class libraries or framework class
libraries. These libraries provide implementations for many general and app-specific types,
algorithms and utility functionality. Both commercial and community libraries build on top of
the framework class libraries, providing easy to use off-the-shelf libraries for a wide set of
computing tasks. A subset of these libraries is provided with each .NET implementation.
Development frameworks and technologies- The .NET Framework includes libraries for
specific areas of application development, such as ASP.NET for web applications, ADO.NET
for data access, and Windows Communication Foundation for service-oriented applications.
Language interoperability- Language compilers that target the .NET Framework generates
an intermediate code named Microsoft Intermediate Language (MSIL), which, in turn, is
12
compiled at run time by the common language runtime. With this feature, routines written in
one language are accessible to other languages, and programmers can focus on creating
applications in their preferred language.
Version compatibility- .NET provides version compatibility, it means applications that are
developed using a particular version of the .NET Framework can run without modification on
a later version.
Side-by-side execution- The .NET Framework helps resolve version conflicts by allowing
multiple versions of the common language runtime to exist on the same computer. This
means that multiple versions of applications can also coexist, and that an application can run
on the version of the .NET Framework with which it was built.
Multitargeting- By targeting the .NET Framework Portable Class Library, developers can
create assemblies that work on multiple .NET Framework platforms, such as the .NET
Framework, Silverlight, Windows Phone 7, or Xbox 360.
Web Development- ASP.NET is a web platform that provides all the services that you
require to build server-based web applications. ASP.NET is built on the .NET Framework, so
all .NET Framework features are available to ASP.NET applications. Your applications can
be written in any language that is compatible with the common language runtime (CLR),
including Visual Basic and C#.
Object Oriented Support- All managed languages in the .NET Framework, such as Visual
Basic and C#, provide full support for object-oriented programming including encapsulation,
inheritance, and polymorphism. Encapsulation means that a group of related properties,
methods, and other members are treated as a single unit or object. Inheritance describes the
ability to create new classes based on an existing class. Polymorphism means that you can
have multiple classes that can be used interchangeably, even though each class implements
the same properties or methods in different ways.
.NET Application for Easy Deployment - One of the main advantages of the .NET
Framework is its new approach to application deployment. Every Microsoft .NET application
will be deployed in the form of one or more assemblies. An assembly is a logical unit of
functionality that is made up of one or more files. One of these files will contain the
assemblies manifest(s). A manifest is the metadata that describes the assembly‘s identity,
publicly exported types, files, and dependencies.
You can choose any programming language that supports the .NET Framework to create your
application. Because the .NET Framework provides language independence and
interoperability, you can interact with other .NET Framework applications and components
regardless of the language with which they were developed.
1. Install the version of the .NET Framework that your application will target. The latest
production version is the .NET Framework 4.5. 13
2. Select the .NET Framework language or languages that you will use to develop your
applications. A large number of languages are available, including Visual Basic, C#, F#, and
C++ from Microsoft.
3. Select and install the development environment that you will use to create your
applications and that supports your selected programming language or languages.
The .NET Framework Architecture is considered as a layered architecture. Figure 1.4 shows
.NET Framework architecture with its components. The lowest layer is the Operating System
on which applications are executed and the upper most layer is the languages supported by
.NET Framework. The intermediate layers are the components of .NET Framework which
help in compiling and executing the programs. The common language runtime layer is the
least abstracted, and closest to the native environment.
Common language runtime (CLR): CLR is the foundation of the .NET Framework. The
runtime manages code at execution time and provide core services such as memory
management, thread management, garbage collection, code verification and remoting. These
benefits are available to any language built for the CLR. This means that the CLR can host a
variety of languages and can offer a common set of tools across those languages.
When a compiler compiles for the CLR, the code is said to be managed code. Managed code 14
is a code that takes advantage of the services offered by the CLR. For the runtime to work
with managed code, that code must contain metadata. This metadata is created during the
compilation process by compilers targeting the CLR. The metadata is stored with the
compiled code and contains information about the types, members, and references in the
code.
The CLR uses this metadata information for specific purpose like:
Locate classes
Load classes
Generate native code
Provide security
The .NET application can be written in any of the programming language supported by .NET
Framework. When we compile the source code, it is not directly converted to native/binary
code; it is first converted into intermediate code known as Microsoft Intermediate Language
(MSIL) code which is then interpreted by the CLR. The compiler also creates the necessary
metadata and compiles it into the component. This MSIL code is CPU independent. After the
MSIL and metadata are in a file, this compiled file is called the portable executable (PE)
code.
The PE file, containing the MSIL can be distributed and placed with the CLR running on the
.NET Framework on any operating system for which the .NET Framework exists, because the
MSIL is platform independent. When you run the MSIL, it is compiled to native code for that
platform. The compilation to native code occurs via another tool of the .NET Framework
called Just-In-Time (JIT) compiler.
The compilation process of converting source code to native code is shown in Figure 1.5.
The CLR includes the Common Type System (CTS) for cross-language type compatibility
and the Common Language Specification (CLS) for ensuring that third-party libraries can be
used from all .NET-enabled languages.
15
Common Type System (CTS): It defines some basic data types. Each .Net compliant
language should map its data types to these standard data types. This makes it possible for all
.Net compliant languages to communicate by passing/receiving parameters with one another.
•It establishes a framework that enables cross-language integration, type safety, and high-
performance code execution.
•It provides an object-oriented model that supports the complete implementation of many
programming languages.
•It defines rules that languages must follow and ensures that objects written in different
languages can interact with each other.
•It provides a library that contains the primitive data types (such as Boolean, Byte, Char,
Int32, and UInt64) and used in application development.
For understanding purpose, let us see some of the naming convention features of CLS that
must be followed by all the languages under .NET Framework:
Signatures: All return and parameter types appearing in a type or member signature must be
CLS-compliant.
The .NET Framework Class Library (FCL): A class library is a collection of methods and
functions that can be used to provide basic functionalities required by the application. The
.NET Framework provides a rich set of standard class libraries called .NET Framework Class
Library (FCL).
For example, Class Library for File handling includes methods to read, write, append or
16
delete content from a file.
Most of these methods are categorized under System.* or Microsoft.* namespaces. A
namespace is a logical segregation of methods. FCL provides different namespaces for
providing a specific set of functionalities.
The common type system defines how types are declared, altered and managed at the
runtime. It provides cross-language type compatibility for all .NET Framework languages.
Classification of Types
The common type system is broadly classified as value type and reference type. In Visual
Basic.NET, data types are implemented based on their classification. The Visual Basic.NET
data types can be classified according to whether a variable of a type stores its own data or a
pointer to the data. If it stores its own data, it is a value type; if it holds a pointer to data
elsewhere in memory it is a reference type.
Value Types
A data type is a value type if it holds the data within its own memory allocation. Value types
include the following:
Every structure is a value type, even if it contains reference type members. For this reason,
value types such as Char and Integer are implemented by .NET Framework structures.
You can declare a value type by using Dim statement along with data type.
Dim x As Decimal
You can also use the New keyword to initialize a value type. This is especially useful if the
type has a constructor that takes parameters.
17
Reference Types
A reference type contains a pointer to another memory location that holds the data. Reference
types include the following:
String
All arrays, even if their elements are value types
Class types
Delegates
A class is a reference type. For this reason, reference types such as Object and String are
supported by .NET Framework classes.
In the given example myBox1 is an object of class Box that stores the reference to the Box
class data members. Since every reference type represents an underlying .NET Framework
class, you must use the New Operator keyword when you initialize it.
End Function
End Class
18
Array is also reference type, even if its members are value types.
The following example shows the difference between reference types and value types.
Program 1.1: To demonstrate the difference between reference and value types.
1 Imports System
2 Class Class1
3 Public Value As Integer = 0
4 End Class
5 Class Test
6 Shared Sub Main()
7 Dim val1 As Integer = 0
8 Dim val2 As Integer = val1
9 val2 = 123
10 Dim ref1 As New Class1()
11 Dim ref2 As Class1 = ref1
12 ref2.Value = 123
13 Console.WriteLine("Values: {0}, {1}", val1, val2)
14 Console.WriteLine("Refs: {0}, {1}", ref1.Value, ref2.Value)
15 End Sub
16 End Class
Output
Values: 0, 123
Refs: 123, 123
Although value types and reference types can be similar in terms of declaration syntax and
usage, their semantics are distinct.
Reference types are stored on the run-time heap; they may only be accessed through a
reference to that storage. Because reference types are always accessed through references,
their lifetime is managed by the .NET Framework. Outstanding references to an instance are
tracked and the instance is destroyed only when no more references remain.
A variable of reference type contains a reference to a value of that type, a value of a more
derived type, or a null value. A null value refers to nothing; it is not possible to do anything
with a null value except assign it.
Assignment to a variable of a reference type creates a copy of the reference rather than a copy
of the referenced value. For a variable of a reference type, the default value is a null value.
Value types are stored directly on the stack, either within an array or within another type;
their storage can only be accessed directly. Because value types are stored directly within
variables, their lifetime is determined by the lifetime of the variable that contain them. When
the location containing a value type instance is destroyed, the value type instance is also 19
destroyed.
Value types are always accessed directly; it is not possible to create a reference to a value
type. Prohibiting such a reference makes it impossible to refer to a value class instance that
has been destroyed. Because value types are always NotInheritable, a variable of a value type
always contains a value of that type. Because of this, the value of a value type cannot be a
null value, nor can it reference an object of a more derived type.
Assignment to a variable of a value type creates a copy of the value being assigned. For a
variable of a value type, the default value is the result of initializing each variable member of
the type to its default value.
Microsoft .Net Assembly is a logical unit of code, that contains code which the Common
Language Runtime (CLR) executes. Assemblies are the building blocks of .NET Framework
applications; they form the fundamental unit of deployment, version control, reuse, activation
scoping, and security permissions. An assembly is a collection of types and resources that are
built to work together and form a logical unit of functionality. An assembly provides the
common language runtime with the information it needs to be aware of type implementations.
To the runtime, a type does not exist outside the context of an assembly. It is the smallest unit
of deployment of a .net application and it can be a .dll or an exe . Assembly is really a
collection of types and resource information that are built to work together and form a logical
unit of functionality.
It include both executable application files that you can run directly from Windows without
the need for any other programs (.exe files), and libraries (.dll files) for use by other
applications. During the compile time Metadata is created with Microsoft Intermediate
Language (MSIL) and stored in a file called Assembly Manifest . Both Metadata and
Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE)
file. Assembly Manifest contains information about itself. This information is called
Assembly Manifest, it contains information about the members, types, references and all the
other data that the runtime needs for execution.
Every Assembly you create contains one or more program files and a Manifest. There are two
types program files: Process Assemblies (EXE) and Library Assemblies (DLL). Each
Assembly can have only one entry point (that is, DllMain, WinMain, or Main).
1. It contains code that the common language runtime executes. Microsoft intermediate
language (MSIL) code in a portable executable (PE) file will not be executed if it does
not have an associated assembly manifest. Note that each assembly can have only one
entry point (that is, DllMain, WinMain, or Main).
2. It forms a security boundary. An assembly is the unit at which permissions are
requested and granted.
3. It forms a type boundary. Every type's identity includes the name of the assembly in
which it resides. A type called MyType loaded in the scope of one assembly is not the
same as a type called MyType loaded in the scope of another assembly.
4. It forms a reference scope boundary. The assembly's manifest contains assembly
metadata that is used for resolving types and satisfying resource requests. It specifies
the types and resources that are exposed outside the assembly. The manifest also
enumerates other assemblies on which it depends.
5. It forms a version boundary. The assembly is the smallest versionable unit in the
common language runtime; all types and resources in the same assembly are
versioned as a unit. The assembly's manifest describes the version dependencies you
specify for any dependent assemblies.
6. It forms a deployment unit. When an application starts, only the assemblies that the
application initially calls must be present. Other assemblies, such as localization
resources or assemblies containing utility classes, can be retrieved on demand. This
allows applications to be kept simple and thin when first downloaded.
7. It is the unit at which side-by-side execution is supported.
Assemblies can be static or dynamic. Static assemblies can include .NET Framework types
(interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource
files, and so on). Static assemblies are stored on disk in portable executable (PE) files. You
can also use the .NET Framework to create dynamic assemblies, which are run directly from
memory and are not saved to disk before execution. You can save dynamic assemblies to disk
after they have executed.
MyAssembly.dll
Assembly Mainfest
Type metadata
MSIL Code
Resources
Alternatively, the elements of an assembly can be contained in several files. These files can
be modules of compiled code (.netmodule), resources (such as .bmp or .jpg files), or other
files required by the application. Create a multifile assembly when you want to combine
modules written in different languages.
Multifile assembly
MyAssembly.dll Util.netmodule
Assembly Mainfest Type metadata
Type metadata MSIL code
MSIL Code
Resources Graphic.bmp
Resources
The files that make up a multifile assembly are not physically linked by the file system.
Rather, they are linked through the assembly manifest and the common language runtime
manages them as a unit.
Every assembly, whether static or dynamic, contains a collection of data that describes how
the elements in the assembly relate to each other. The assembly manifest contains this
assembly metadata. An assembly manifest contains all the metadata needed to specify the
assembly‘s version requirements and security identity, and all metadata needed to define the
scope of the assembly and resolve references to resources and classes. The assembly manifest
can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL)
code or in a standalone PE file that contains only assembly manifest information.
The .NET Framework's garbage collector manages the allocation and release of memory for
your application. Each time you use the new operator to create an object, the runtime
22
allocates memory for the object from the managed heap. As long as address space is available
in the managed heap, the runtime continues to allocate space for new objects. However,
memory is not infinite. Eventually the garbage collector must perform a collection in order to
free some memory. The garbage collector's optimizing engine determines the best time to
perform a collection, based upon the allocations being made. When the garbage collector
performs a collection, it checks for objects in the managed heap that are no longer being used
by the application and performs the necessary operations to reclaim their memory.
The .NET garbage collector provides a high-speed allocation service with good use of
memory and no long-term fragmentation problems. The garbage collector follows a simple
model of the managed heap as shown below.
Uncommitted (Reserved)
Free Space
All garbage-collectable objects are allocated from one contiguous range of address
space.
The heap is divided into generations so that it is possible to eliminate most of the
garbage by looking at only a small fraction of the heap.
Objects within a generation are all roughly the same age.
Higher-numbered generations indicate areas of the heap with older objects—those
objects are much more likely to be stable.
The oldest objects are at the lowest addresses, while new objects are created at
increasing addresses.
The allocation pointer for new objects marks the boundary between the used
(allocated) and unused (free) areas of memory.
Periodically the heap is compacted by removing dead objects and sliding the live
objects up toward the low-address end of the heap. This expands the unused area at
the bottom of the diagram in which new objects are created.
The order of objects in memory remains the order in which they were created, for
good locality.
23
There are never any gaps between objects in the heap.
Only some of the free space is committed. When necessary, more memory is acquired
from the operating system in the reserved address range.
The garbage collector is a common language runtime component that controls the allocation
and release of managed memory. The methods in this class are executed when memory
allocation is performed on an object and when resources allocated by an object are released.
Properties in this class provide information about the total amount of memory available in the
system and the age category, or generation, of memory allocated to an object.
The garbage collector tracks and reclaims objects allocated in managed memory.
Periodically, the garbage collector performs garbage collection to reclaim memory allocated
to objects for which there are no valid references. Garbage collection happens automatically
when a request for memory cannot be satisfied using available free memory. Alternatively, an
application can force garbage collection using the Collect method.
Before After
Free Space
Allocating Memory
When you initialize a new process, the runtime reserves a contiguous region of address space
for the process. This reserved address space is called the managed heap. The managed heap
maintains a pointer to the address where the next object in the heap will be allocated.
Initially, this pointer is set to the managed heap's base address. The managed heap is used to
allocate all reference types. When an application creates the first reference type, memory is
allocated for the type at the base address of the managed heap. When the application creates
the next object, the garbage collector allocates memory for it in the address space
immediately following the first object. As long as address space is available, the garbage
collector continues to allocate space for new objects in this manner. 24
Allocating memory from the managed heap is faster than unmanaged memory allocation.
Because the runtime allocates memory for an object by adding a value to a pointer, it is
almost as fast as allocating memory from the stack. In addition, because new objects that are
allocated one after the other are stored contiguously in the managed heap, an application can
access the objects very quickly.
Releasing Memory
The garbage collector's optimizing engine determines the best time to perform a collection
based on the allocations being made. When the garbage collector performs a collection, it
releases the memory for objects that are no longer being used by the application. It
determines which objects are no longer being used by examining the roots of application.
Each root of an application either refers to an object on the managed heap or is set to null. An
application's roots include static fields, local variables and parameters on a thread's stack, and
CPU registers. The garbage collector has access to the list of active roots that are maintained
by the just-in-time (JIT) compiler and the runtime. Using this list, the garbage collector
examines an application's roots, and in the process creates a graph that contains all the objects
that are reachable from the roots.
Objects that are not available in the graph are unreachable from the application's roots. The
garbage collector considers unreachable objects garbage and releases the memory allocated
for them. During a collection process, the garbage collector examines the managed heap,
looking for the blocks of address space occupied by unreachable objects. As it discovers each
unreachable object, it uses a memory-copying function to compact the reachable objects in
memory, freeing up the blocks of address spaces allocated to unreachable objects. Once the
memory for the reachable objects has been compacted, the garbage collector makes the
necessary pointer corrections so that the application's roots point to the objects in their new
locations. It also positions the managed heap's pointer after the last reachable object. The
memory is compacted only if a collection discovers a major number of unreachable objects.
If all the objects in the managed heap survive a collection, then there is no need for memory
compaction.
The garbage collector in the common language runtime supports object aging using
generations. A generation is a unit of measure of the relative age of objects in memory. The
generation number, or age, of an object indicates the generation to which an object belongs.
Objects created more recently are part of newer generations, and have lower generation
numbers than objects created earlier in the application life cycle. Objects in the most recent
generation are in generation 0. This implementation of the garbage collector supports three
generations of objects, generations 0, 1, and 2. You can retrieve the value of the
MaxGeneration property to determine the maximum generation number supported by the
system.
Object aging allows applications to target garbage collection at a specific set of generations
rather than requiring the garbage collector to evaluate all generations. Overloads of the 25
Collect method that include a generation parameter allow you to specify the oldest generation
to be garbage collected.
Benefits of Garbage Collection:
It allows you to develop your application without having to consider about freeing
memory.
It does allocation objects on the managed heap efficiently.
It also reclaims objects that are no longer being used and clears their memory and
keeps the memory available for future allocations. Managed objects automatically get
clean content to start with, so their constructors do not have to initialize every data
field.
It provides memory safety by making sure that an object cannot use the contents of
another object.
Exception handling allows you to manage run-time errors in an orderly fashion. Using
exception handling, your program can automatically invoke an error-handling routine when
an error occurs. The principal advantage of exception handling is that it automates much of
the error-handling code that previously had to be coded "by hand" in any large program.
Structured exception handling is significantly more versatile, robust, and flexible than
unstructured. Structured exception handling should be preferred over unstructured exception
handling. Unstructured exception handling can be used under the following circumstances:
You are upgrading an application written in an earlier version of Visual Basic.
You are developing an introductory version of an application and you don't mind if
the program fails to shut down gracefully.
You know in advance exactly what will cause the exception.
In case a deadline is near and you need to take shortcuts.
Code is trivial or so short that you only need to test the branch of code generating the
exception.
You need to use the Resume Next statement, which is not supported in structured
exception handling.
Structured and unstructured exception handling cannot be combined in the same function. If
you use an On Error statement, you cannot use a Try...Catch statement in the same function.
When an exception occurs in a try block, the system searches the associated catch blocks in
the order they appear in application code, until it locates a catch block that handles the
exception. A catch block handles an exception of type T if the type filter of the catch block
specifies T or any type that T derives from. The system stops searching after it finds the first
catch block that handles the exception. For this reason, in application code, a catch block
that handles a type must be specified before a catch block that handles its base types, as
demonstrated in the example that follows this section. A catch block that handles
System.Exception is specified last.
Try
throw
Catch ex As Exception
//catch statement
Finally
//finally block
End Try
The above program code explains the simplest form of structured exception handling.
At line 11 demonstrates the use of throw statement, based on the condition (num3<10),
program throws exception using throw keyword. System Exception is captured in second
catch block at line 14. Since, first exception blow captures error related to Arithmetic
Exception as mentioned in the output of the above program.
You can create our own exception in the application based on the specific requirement and
throw the exception when some requirements are violated.
However, A Catch clause can take three possible forms: Catch, Catch...As, and
Catch...When.
A Catch clause with no When keyword allows the associated statement block to handle any
exception.
Catch...As and Catch...When clauses catch a specific exception and allow the associated
statement block to tell the application what to do.
You must note that Catch...As and Catch...When clauses can also be combined in a single
statement, such as Catch ex As Exception When intResult <> 0.
If the exception is a result of resource failure, it should identify the resource and, if possible,
provide troubleshooting advice. If the exception is a result of a failure of programming logic,
the clause should allow the application to exit as gracefully as possible. If user error has
caused the exception, however, the code should allow the user to correct his or her error and
proceed.
Catch clauses are checked in the order in which they appear in the code. Therefore, catch
clauses should move from the specific to the general as they progress through the sequence of
code. Check a type before checking its base type, for example. A catch block handling
System.Exception should only appear as a final block after the other possibilities have been
exhausted. 28
Exception Object
The Exception object provides information about any encountered exception. Whenever an
exception is thrown, the properties of the Err object are set, and a new instance of the
Exception object is created. Examine its properties to determine the code location, type, and
cause of the exception.
Following are some useful properties of the Exception object:
The HelpLink property can hold an URL that points the user to further information about the
exception.
The HResult property gets or sets HRESULT, a numerical value assigned to the exception.
HRESULT is a 32-bit value that contains three fields: a severity code, a facility code, and an
error code. The severity code indicates whether the return value represents information, a
warning, or an error. The facility code identifies the area of the system responsible for the
exception. The error code is a unique number assigned to represent the error.
The InnerException property returns an exception object representing an exception that was
already in the process of being handled when the current exception was thrown. The code
handling the outer exception may be able to use the information from the inner exception in
order to handle the outer expression with greater precision.
The Message property holds a string, which is the text message that informs the user of the
nature of the error and the best way or ways to address it. During the creation of an exception
object, you can provide the string best suited to that particular exception. If none is provided,
the default string will be provided and formatted according to the current culture.
The Source property gets or sets a string containing the name of the object throwing the
exception or the name of the assembly where the exception occurred.
The StackTrace property holds a stack trace, which you can use to determine where in the
code the error occurred. StackTrace lists all the called methods that preceded the exception
and the line numbers in the source where the calls were made.
The TargetSite property gets the method name that threw the current exception. If the name is
not available and the stack trace is not Nothing, the TargetSite property obtains the method
name from the stack trace.
There are two defined subclasses of exceptions in the Exception base class:
System.Exception and Application.Exception.
System.Exception is the class from which the .NET Framework derives the pre-defined
common language runtime exception classes. It is thrown by the common language runtime
when nonfatal errors occur. System.Exception does not provide information about the cause
of the exception.
We can create our own application exception classes by inheriting them from the
Application.Exception class. The following example shows how to create user defined
exception and how to throw user defined exception in an application. 29
Program 1.3: TO demonstrate creating user defined exception in the application
1 Module Module1
2 Sub Main()
3 Dim age As Integer
4 Try
5 System.Console.WriteLine("Enter Age")
6 age = System.Console.ReadLine()
7 If age <= 0 Then
8 Throw New AgeIsZeroException("Age Can't be less than zero")
9 End If
10 Catch e As AgeIsZeroException
11 System.Console.WriteLine("Error raised:" + e.ToString)
12 Catch e As Exception
13 System.Console.WriteLine("Error raised:" + e.ToString)
14 Finally
15 System.Console.ReadKey()
16 End Try
17 End Sub
18 End Module
19
20 Public Class AgeIsZeroException : Inherits ApplicationException
21 Public Sub New(ByVal message As String)
22 MyBase.New(message)
23 End Sub
24 End Class
25
26
27
Output:
Enter Age -1
Error raised: ConsoleApplication1.AgeIsZeroException:Age Can‘t be less than zero
The above program creates an user defined exception class named ―AgeIsZeroException‖
which is inherited from ApplicationException class. The user defined exception is not thrown
by the application, you need to throw specific exception based on certain condition. Line No
7 checks the age entered by user, if user has entered zero or less value then
AgeIsZeroException is thrown and program control jumps to the Catch Block at line no 10
and the corresponding error message is displayed.
The values of the properties of the Err object are determined by the error that just occurred.
Table 1.1 details the properties and provides a short description of each.
The above program handles the exception in an unstructured mode by writing On Error
Resume Next, it let the program continue with the next statement whenever any error is
encountered. The use of this statement is not considered good practice for application
development. However, it can be used when we are testing a part of the module rather than
complete application.
On Error GoTo Label statement allows the control to move to a block where we can write
corresponding error handling code, and make it look like structured exception handling.
In the above program upon encountering any error the control moves to lbl and relevant
message is displayed to the user.
The On Error GoTo statement enables a routine for exception handling and specifies the
32
location of that routine within the procedure. It is used with a label or line number, and it
directs the code to a specific exception handling routine. When used with -1, it disables error
handling within the procedure. When used with 0, it disables the current exception. If there is
no On Error statement and the exception is not handled by any methods in the current call
stack, then any run-time error that occurs is fatal: execution stops and an error message is
displayed. Table 1.2 shows the ways the On Error GoTo Statement may be used.
The Resume statement by itself can return control to the statement that caused the exception.
The execution resumes at the same line that initially raised the exception.
By contrast, the Resume Next statement resumes execution after an exception has occurred.
It specifies that in the event of an exception, control passes to the statement immediately
following the statement in which the exception occurred. Resume Next can be used to allow
graceful failures; the statement causing the error fails, but the application continues to
execute and allows the user to correct the error and continue. Similarly, Resume <label>
passes control to a label specified in its line argument. We should make sure that the line
label is located in the same procedure as the code calling it, since it cannot span between
functions.
Resume must be used exclusively in error handling routines. Outside such routines, it causes
an error.
The Error statement is supported in Visual Basic .NET only for backwards compatibility. In
new code, use the Err object's Raise method to generate run-time errors.
The .NET Security Model provides code access permissions and code identity permissions.
Code Access Security is the part of the .NET security model that determines whether or not
the code is allowed to run, and what resources it can use when it is running. Code Access
Security policy uses evidence to help grant the right permissions to the right assembly.
33
An administrator can configure Code Access Security policy to restrict the resource types that
code can access and the other privileged operations it can perform. Code Access Security
allows code to be trusted to varying degrees depending on where the code originates and on
other aspects of the code's identity. Code Access Security can also help minimize the damage
that can result from security vulnerabilities in your code.
Code Access Security enables users to restrict, on a very granular level, what managed code
can do according to a level of trust. If the CLR trusts the code enough to allow it to run then it
will begin executing the code depending on the permissions given to the assembly. If the
code is not trusted and attempts to perform some action it does not have relevant rights for
then a security exception is thrown.
It is important to understand that code access security is about protecting resources, such as
directories, local drives, event logs, user interface and the network from malicious code. It is
not primarily a tool for protecting software from users.
Code Access Security can be applied only to managed applications. Unmanaged applications
run without any CAS restrictions and are limited only by the operating system's role-based
security. If CAS is used to restrict the permissions of an assembly then the assembly is
considered partially trusted. Partially trusted assemblies must undergo CAS permission
checks each time they access a protected resource. Fully trusted assemblies, like unmanaged
code, can access any system resource that the user has permissions to access.
1. Code Group
The evidence provided by an assembly is used as the condition for granting and
revoking permissions to it. It is done by putting the code in an appropriate code group.
Every code group stipulates a membership condition and has specific conditions
attached to it. Any assemblies that meet the condition become a member of the group.
Code groups are arranged in a hierarchy and assemblies are nearly always matched to
several code groups. The code group at the root of the hierarchy is called All Code
and contains all other code groups.
2. Evidence
In order for the CLR to determine which code group to place assembly information
into, the first step is to read supplied evidence. There are two main sources of
information, they are Internet and Intranet. The group Internet defines code that is
sources from the Internet and the group Intranet defines code sources from a LAN.
The examination of the assembly evidence makes the authentication part of the
security process. Table 1.3 depicts the major types of evidence an assembly can
present to the CLR.
Table 1.3: Major types of evidence assembly can present to the CLR
Evidence Description
The region such as intranet, local, trusted from which the
Zone code originated. 34
URL The specific URL from which the code originated.
Strong Name Unique verifiable name for the code.
Site The website from which the code originated.
Harsh Value The hash value of the assembly contents.
The assembly digital signature that uniquely identified the
Publisher developer.
Application
Directory The directory in which assembly resides.
The region such as intranet, local, trusted from which the
Zone code originated.
3. Permissions
Permissions are the actions you allow each code group to perform. The system
administrator usually manages the permissions at the enterprise, machine and user
levels. The CLR Virtual Execution System (VES) loads and runs programs. It
provides the functionality required to execute managed code and uses assembly
metadata to connect modules together at runtime. When VES loads an assembly, it
matches the assembly to one or more code groups. Each code group is assigned to one
or more permissions that specify what actions assemblies can do in that code group.
Conclusion
One of the primary features of any application design is the system architecture. The system
architecture defines how different parts of the application interact with each other, and what
functionality each part is responsible for performing. Based on the type of functionality it is
broadly divided it into three categories: User service, business service and data service.
Application is categorized as Single tier when all the services are grouped in single system,
similarly application can be two tier or three tier.
The .NET Framework is an application development platform that provides services for
building, deploying, and running desktop, phone and web applications and web services. It
consists of the common language runtime (CLR), Common Type system (CTS), Common
Language Specifications (CLS) to provide object oriented development environment for
developing different types of application using different language under single framework.
It provides memory management and other system services, and an extensive class library,
which includes code for major areas of application development.
Progress Check
1. The … is the execution engine for .NET applications and servers as the interface between .NET
applications and the operating system.
A) Common Language Specifications (CLS)
35
B) Common Language Runtime (CLR)
C) Common Type System (CTS)
D) Framework Class Library (FCL)
3. State whether the following statements about .NET Frameworks are TRUE or FALSE.
i) The .NET FCL is object-oriented.
ii) The CLR is the platform on which applications hosted and executed.
A) i-True, ii-False
B) i-False, ii-True
C) i-True, ii-True
D) i-False, ii-False
4. The .NET … is a collection of reusable types that are integrated with the CLR.
A) Common Language Specifications (CLS)
B) Common Language Runtime (CLR)
C) Common Type System (CTS)
D) Framework Class Library (FCL)
5. … is an agreement among language designers and class library designers to use a common
subset of basic language features that all languages have to follow.
A) Common Language Specifications (CLS)
B) Common Language Runtime (CLR)
C) Common Type System (CTS)
D) Framework Class Library (FCL)
6. … describes how types are declared, used, and managed in the runtime.
A) Common Language Specifications (CLS)
B) Common Language Runtime (CLR)
C) Common Type System (CTS)
D) Framework Class Library (FCL)
7. State which of the following statements about the .NET framework are TRUE.
i) CTS helps developers to develop applications in a single language.
ii) Data and XML classes extend the FCL to support data management and XML manipulation.
iii) XML classes support various operations on XML data like searching, translations, modifying,
etc.
A) i and ii only
B) ii and iii only
C) i and iii only
D) All i, ii and iii 36
8. … is a code that consists of CPU and platform-independent set of instructions, which can be
easily converted to native code.
A) JIT
B) FCL
C) DLL
D) MSIL
9. State whether the following statements about the Microsoft Intermediate Language (MSIL) are
TRUE or FALSE.
i) The MSIL code includes instructions to load, initialize and invoke methods on objects.
ii) The MSIL code is collected and assembled in the form of byte codes and is converted to a .NET
assembly.
A) i-True, ii-False
B) i-False, ii-True
C) i-True, ii-True
D) i-False, ii-False
10. The main function of … is to convert the managed code into native code and then execute the
code.
A) CLR
B) CTS
C) CLS
D) FCL
11. Which of the following is/are the modules of Common Language Runtime(CLR).
i) Thread Support
ii) Type Checker
iii) Security Engine
A) i and ii only
B) ii and iii only
C) i and iii only
D) All i, ii and iii
12. … will verify types used in the application with CTS or CLS standards supported by CLR.
A) Exception manager
B) Type checker
C) Code manager
D) Class loader
15. State whether the following statements about the managed and unmanaged code are TRUE or
FALSE.
i) Managed code is the code that is executed directly by the CLR.
ii) Managed code directly compiles to the machine code and runs on the machine where it has to be
compiled.
iii) Unmanaged code does not have services such as security or memory management.
A) i-True, ii-False, iii-False
B) i-False, ii-True, iii-False
C) i-True, ii-False, iii-True
D) i-False, ii-False, iii-True
16. ___ ensures complete interoperability among applications, regardless of the language used to
create the application.
A) CLR
B) CLS
C) CTS
D) FCL
17. State which of the following statements about the Namespace are TRUE.
i) All the classes and types of .NET FCL are organized in the namespace.
ii) Namespaces correspond to file or directory names.
iii) It is the grouping of logically related identifiers or classes.
A) i and ii only
B) ii and iii only
C) i and iii only
D) All i, ii and iii
18. The … namespace includes classes and interfaces that define the various collections of objects
such as lists, queues, hash tables, arrays, etc.
A) system.collection
B) system
C) system.data
D) system.drawing
38
19. The … namespace includes classes that allow us to debug our application and to step through
our code.
A) system.collection
B) system.security
C) system.diagnostics
D) system.threading
20. The … namespace includes classes and interfaces that return information about types, methods,
and fields.
A) system
B) system.security
C) system.data
D) system.reflection
Answers;
1) Visual Basic 2010 programming Black Book, by Kogent Learning Solutions, Wiley
India
2) Visual Basic 2010 Step By Step, Michael Halvorson, PHI
References:
1) Mastering Microsoft Visual Basic 2010, Evangelos Petroutsos, Wiley Publications
2) Beginning Visual Basic 2010 (Wrox)
40
Chapter 2: Introduction to Visual Basic.Net IDE
Learning Outcomes of the unit:
2.1 Introduction
Feature Description
Annotations Allows developer to extract C# annotations and render them in HTML or
reporting store them in XML documents
Auto-hide Allows developer to stow minimized documents along the edges of the
development environment and pops up docs as developer mouse-over
them
Cascading Style Full support for creating styles that can be applied to HTML or XML
Sheets elements
Command window Allows developer to invoke commands within the IDE
Debugging support Enhanced debugging support for C#, C++, and Visual Basic directly in
the environment, as well as support for managed-code and remote
debugging
Deployment tools Allows developer to take advantage of Windows Installer to deploy
applications; supports installation rollback and app advertising; graphical
editor allows developer to create installers; merge modules
allow developer to standardize component installation for multiple apps
Document Maintains such things as cursor history, allowing developer to navigate
navigation back to parts of a document or to different windows
Editor features Too numerous to cover; includes auto-indent, color highlighting, auto-
complete, clipboard rings, document navigation, and many more
Enhanced Allows developer to access and control parts of the IDE
automation support programmatically, such as the Code Editor, projects, tool windows, and
debugging, building, and deployment tools
HTML WYSIWYG design and source code editing of HTML documents
Macro recording Allows developer to record and play macros directly in the development
environment
Object browser Supports all languages and allows developer to browse objects in projects,
class libraries, and and so forth
Schemas Supports the automatic creation of a schema from an XML document
instance
Start page Acts as a personal home page for developer .Net development and
provides access to news, updates, downloads, and documentation
Tabbed documents Allows developer to tab through multiple windows in one part of the
screen
Web browser Allows developer to display Web pages directly in the development
environment
XML Allows developer to edit XML with syntax-directed highlighting
Data types The Deftype statements (DefBool, DefByte, and so on) are not supported.
Currency type is replaced by Decimal type. Dates are now stored as 8-
byte integers, matching the CLR DateTime type.
Dim, ReDim Developer can no longer use ReDim in an initial array declaration.
Developer must first declare the array using Dim. The array can then be
resized using ReDim.
Integers Short refers to a 16-bit signed integer. Integer (type character %) now 42
refers to a 32-bit signed integer. Long (type character &) refers to a 64-bit
signed integer.
Strings The string data type now corresponds to the .NET Framework String
class, which cannot be modified after initialization. If strings must be
modified, the StringBuilder class is used.
Variable scope Variables declared in blocks have a block scope rather than a procedure
scope. Variables declared in procedures but not within a block (a set of
statements terminated by End, Loop, or Next) will have a procedure
scope.
Variants Variant is replaced by the keyword Object. Variant, however, remains a
keyword in the language.
A Visual Basic Project is container for the forms, methods, classes, controls that are used for
and Visual Basic Application.
Click on the Programs->Microsoft Visual Studio.net 2008, to get the following window.
43
Choose File->New Project from the Menu Bar to get the New Project window.
Select the type of Project as per the requirement from following choices Windows
Application,Class Library, Console Application,Windows Control Library, Web
Control Library,Windows Service, Empty Project,Crystal Reports.
To develop a Windows Based Application Choose Windows Application fill in a Name for
the application
44
By default, a project named My Project and a form Form1 will be created. Project name
and form name can be renamed later.
45
2.3 Types of projects in .NET :
The Following are some the different projects that can be created with Visual Studio.NET:
1)Console applications
2)Windows Applications
3)Web applications
4)Web services
5)Class library
6)Windows Control Library
7)Web Control Library
1) Console applications are light weight programs run inside the command prompt (DOS)
window. They are commonly used for test applications.
2)Windows Applications are form based standard Windows desktop applications for common
day to day tasks. (Ex: Microsoft word).
3)Web applications are programs that used to run inside some web server (Ex:IIS) to fulfill
the user requests over the http. (Ex: Hotmail and Google).
4)Web services are web applications that provide services to other applications over the
internet.
5)Class library contains components and libraries to be used inside other applications. A
Class library can not be executed and thus it does not have any entry point.
6)Windows Control Library contains user defined windows controls to be used by Windows
applications.
7)Web Control Library contains user defined web controls to be used by web applications.
In this topics we have to discuss the working of solutions explorer window, how to write the
code for a particular project, toolbox and their controls, properties windows and how to use it
and output windows of .NET IDE.
Coding in project : VB .Net is an event driven i.e. When an event is executed the project
goes to the current event procedure. Event-handling procedures are Sub procedures that
execute in response to an event raised by user action or by an occurrence in a program. This
is the area where actual programming is done. We can view the event procedure in code
window. You can also get the view code in the solution explorer window. You can also write
the code by using view menu and then click code. You can press F7 key to open directly code 46
window.
2.5 Solution Explorer Window :
The solution explorer windows lists of all the files which are associated with a project. It is
lying on the right under the toolbar in the VB IDE. This window list all forms and current
projects. We can add more window form, class module, class etch in the current application
by using solution explorer window. In VB 6 this was known as Project Solution.
2.6 ToolBox :
The Toolbox is a palette of controls (command buttons, checkboxes, textboxes, listboxes, and
comboboxes) that you can drag-and drop onto a user form that you are building. Each control
on the toolbox is class that belongs to system, windows, form namespace.
47
2.7 Properties Windows :
The Properties window displays the properties of single or multiple selected items. If
multiple items are selected, the intersection of all properties for all selected objects is
displayed. property window can support typically numerous tasks rather than a single task. It
is also used to display properties for objects selected in the two main types of windows.
tool windows such as Solution Explorer, Class View, and Object browser
Document windows containing such editors and designers as the forms designer, XML
editor, and HTML editor
Code Editor : it is the area where most of the code is written. To view code window either
double click or press F7 key or select view and code.
The Output window displays status messages for various features in the integrated
development environment (IDE).
To open the Output window, on the menu bar, choose View > Output, or press
Ctrl+Alt+O.
Show output from: Displays one or more output panes to view. Several panes of information
might be available, depending on which tools in the IDE have used the Output window to
deliver messages to the user.
Find Message in Code: Moves the insertion point in the code editor to the line that contains 48
the selected build error.
Go to Previous Message: Changes the focus in the Output window to the previous build error
and moves the insertion point in the code editor to the line that contains that build error.
Go to Next Message: Changes the focus in the Output window to the next build error and
moves the insertion point in the code editor to the line that contains that build error.
Toggle Word Wrap: Turns the Word Wrap feature on and off in the Output pane. When
Word Wrap is on, text in longer entries that extends beyond the viewing area is displayed on
the following line.
The Object Browser allows us to browse through the various properties, events and methods
that are made available to us.
49
It is accessed by selecting Object Browser from the View menu or pressing the key F2.
The left column of the Object Browser lists the objects and classes that are available in the
projects that are opened and the controls that have been referenced in them.
After an object is picked up from the Classes list, we can see its members (properties,
methods and events) in the right column.
Conclusion
50
In this unit we learnt about Dot Net IDE, types of projects in VB, solution explorer and
properties of windows.
Chapter 3:VB.Net Programming Language
Learning Outcomes of the unit:
Understand the similarities and differences with visual basic, variables, comments
and data types.
Discuss Arrays and ArraysLists
Discuss Multidimensional Arrays
Describe Enumerations
Describe Structures
Describe Decision Constructs
Describe Iterative Constructs
Implement Decision Constructs
Implement Iterative Constructs
Describe the Exit Statement
VB.Net
• Software platform
• Language neutral
• In other words:
.NET is not a language (Runtime and a library for writing and executing written programs
in any compliant language)
Using variables
Variables can be initialized or assigned a value anywhere within the program after they have
been declared.
Examples of datatypes
Dim d1 As Double
Dim d2 As Object
Dim d3, d4, d5 As Integer
Dim mystring As String
Dim a As Integer = 5
d1 = 12
d2 = ―10.5‖
d3 = 4 52
mystring = ―Jonathan‖
Simple VB.NET program
Module Module1
Sub Main()
Dim a As Integer
Dim b As Decimal
Dim c As Char
Dim d As Single
a = 100
b = 9.5003127
c = ―M‖
d = 0.000054887
System.Console.WriteLine (―Integer ― &a)
System.Console.WriteLine (―Decimal ― &b)
System.Console.WriteLine (―Char ― &c)
System.Console.WriteLine (―Single ―&d)
End Sub
End Module
3.4 Constants
Constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are also enumeration constants
as well.
The constants are treated just like regular variables except that their values cannot be
modified after their definition.
An enumeration is a set of named integer constants.
Constants are declared using the Const statement.
The Const statement is used at module, class, structure, procedure, or block level for
use in place of literal values (or fixed values).
Module constantsNenum
Sub Main()
Const PI = 3.14149
Dim radius, area As Single
radius = 7
area = PI * radius * radius
Console.WriteLine("Area = " & Str(area))
Console.ReadKey()
End Sub
End Module
OUTPUT:
Area = 153.933
Print and Display Constants in VB.Net
54
3.5 Comments
55
56
3.6 Data types in VB.NET
Byte 8 -bit
Range: 0 to 255.
Short
16 bit Range: –32768 to +32767
Boolean 16 bit
Represents numbers as True or False
31
String - Can store 2^ Unicode characters.
Option Statement
Option Strict
Option Strict On
Module Module1
Sub Main( )
Dim num1 As Single
Dim num2 As Double
num2 = 5.5
num1 = num2
System.Console.WriteLine(num1)
End Sub
End Module
Note:--The program will fail to compile because here typecasting will not take place
Demonstrating Typecasting
Option Strict On
Module Module1
Sub Main()
Dim num1 As Single
Dim num2 As Double
num2 = 5.5
num1 = CType(num2,Single)
‗Had the CType function not been used
‗the program would not have compiled
System.Console.WriteLine(num1)
End Sub
End Module 58
EmpData(0) = "astalavista"
EmpData(2) = 100
Mixing data types in an array is possible if it is declared of type Object. The following
example stores employee information in the array variable EmployeeData.
MDim0 = MatA.GetLength(0) – 1
MDim1 = MatA.GetLength(1) - 1
Next Num2
59
Next Num1
Redim statement
The above statement allocates a new array, initializes its elements from the corresponding
elements of the existing MyArray, and assigns the new array to MyArray.
Multidimensional Arrays
• An array can have a maximum of 32 dimensions though we rarely use more than three
dimensions.
• The total size of a multidimensional array is the product of the sizes of all the
dimensions of the array.
Module m
Sub Main( )
Dim a(2,2) As Integer
Dim i As Integer
Dim j As Integer
For i = 0 To 2
For j=0 to 2
a(i,j)=System.Console.Readline()
Next
Next
System.Console.WriteLine("The array is ")
For i = 0 To 2
For j=0 to 2
System.Console.WriteLine(a(i,j) & " ")
Next
System.Console.WriteLine( )
Next
End Sub 60
End module
Redim Preserve
...
...
Using an index position that exceeds the limit of the array will cause an
IndexOutOfRangeException.
Module m
Sub Main()
Dim i As Integer
For i = 0 To 3
System.Console.WriteLine(values(i))
next
End Sub
End Module
61
3.8 Array Lists
3.9 Enumerations
Enumerations are used when we need to refer to values of primitive types such as Byte,
Short, Integer and Long as constants or literals.
Value1
Value2
...
End Enum
Using Enumerations
Illinois
Denver
Plano
Austin 62
End Enum
Here ,
Illinois0
Denver1
The member Plano could be used as
UserCity = Cities.Plano
Assuming, UserCity is declared as a variable of Short type.
Demonstrating Enumerations
Module m
Illinois
Denver
Plano
Austin
End Enum
Sub Main()
System.Console.WriteLine(Cities.Plano)
End Sub
End Module
Illinois
Denver
Plano
Austin=Denver
End Enum
A=100
B=80
C=70
D=60
E=40
End Enum
Module m
Sub Main()
System.Console.WriteLine("Enter marks")
gradevalue=System.Console.ReadLine()
Case grade.A
System.Console.WriteLine("A")
Case grade.B
System.Console.WriteLine ("B")
Case grade.C
System.Console.WriteLine ("C")
Case grade.D
System.Console.WriteLine ("D")
Case Else
System.Console.WriteLine ("Fail")
End select
End Sub
64
End module
3.10 Structures
• A structure is a composite user-defined data type using which we can group data of
different data types together.
• A structure can hold not only fields but also methods, properties and events.
Structure
[Variable declarations]
[Procedure Declarations]
End Structure
Using Structures
Module m
End structure
Sub Main()
b.Title=System.Console.ReadLine()
b.Author=System.Console.ReadLine()
b.Pages=System.Console.ReadLine()
b.Price=System.Console.ReadLine()
End Sub
End Module
Module m 65
Public Structure X
Public Y as Integer
End Structure
Sub Main()
Dim Obj as X
Dim i as Integer
Obj.Arr(0)=150
Obj.Arr(1)=200
System.Console.WriteLine(Obj.Arr(0))
System.Console.WriteLine(Obj.Arr(1))
End Sub
End Module
Module m
Structure stud
Name=System.Console.ReadLine()
rollno=System.Console.ReadLine()
End sub
End structure
Sub main()
Dim s as stud
66
s.accept()
System.Console.WriteLine("The student details are ")
System.Console.WriteLine(s.name)
System.Console.WriteLine(s.rollno)
End sub
End module
Module m
Structure dateofbirth
End structure
Structure stud
name=System.Console.ReadLine()
rollno=System.Console.ReadLine()
End Sub
Dob.Day= System.Console.ReadLine()
Dob.Month= System.Console.ReadLine()
Dob.Year= System.Console.ReadLine()
End sub
67
End Structure
Sub main()
Dim s as stud
s.accept()
s.acceptdob()
System.Console.WriteLine(s.name)
System.console.writeLine(s.rollno)
System.Console.WriteLine(s.dob.year)
End sub
End module
Code snippets written for a particular process which is to be executed many times
from different parts of the program
Avoid repetition of the same code in many places for the same purpose Save time and
memory
A Sub procedure is called using the procedure name, followed by the argument list in
parentheses.
A Sub procedure can accept arguments; however, it cannot return a value to the
calling procedure.
Sub subname[(argumentlist)]
Statements
End Sub
Example:--
Module M
Sub main( )
Dim j as Integer
j=System.Console.Readline()
End Sub
System.Console.WriteLine(x*x)
End Sub
End Module
Any number of Exit Sub statements can appear anywhere in the procedure.
It is also possible to use the Return statement to immediately exit the procedure.
1)Module M
Sub Main( )
attendance=System.Console.ReadLine( )
total(attendance)
End Sub
Sub total(x as Char)
Dim marks1 as Integer
If x="A" or X="I"
Exit Sub
End If
System.Console.WriteLine("Enter 3 marks")
marks1=System.Console.ReadLine( )
marks2=System.Console.ReadLine( )
marks3=System.Console.ReadLine( )
ave=(marks1+marks2+marks3)/3
End Sub
End Module 70
2) Sub SubComputeArea(ByVal Len As Double, ByVal Wid As Double)
Function Procedures return values whereas Sub Procedures cannot return a value to
the calling procedure.
Calling functions
• A function can also be called using the Call statement, in which case the return value
is ignored.
71
Example:--
Module M
Sub Main( )
Dim num as Integer
Dim f as Long
System.Console.WriteLine("Enter a number")
num=System.console.Readline( )
f=factorial(num)
System.Console.WriteLine("factorial is "&f)
End Sub
Function factorial(x as Integer)
Dim fact as Long
Dim i as Integer
fact=1
For i=1 to x
fact=fact*i
Next i
Return fact
End Function
End Module
Passing arguments
Arguments can be passed to functions and procedures in VB.NET using the ByVal or ByRef
keywords. If we do not specify any of these keywords, it is assumed to be ByVal.
The ByVal keyword is used to pass an argument by value. It indicates that the value of the
variable should not be modified by the called procedure or function.
Example:--
Module m 72
The ByRef keyword is used to indicate that the arguments are passed by reference and not
value. This means that the called procedure or function can modify or change the variable.
Module M
Sub Increment(ByRef x As Integer)
x=x+2
System.Console.WriteLine(―The value is {0}‖,x)
End Sub
Sub main()
Dim n As Integer
n = 10
System.Console.WriteLine(―The value within procedure is {0}‖, n)
Increment (n)
System.Console.WriteLine(―The value in main is {0}‖, n)
End Sub
End Module 73
Optional arguments
• Every optional argument in the procedure definition must specify a default value,
which must be a constant.
Syntax :
We could supply the first and fourth arguments but omit the second or third arguments.
Sub Notify (ByVal Company As String, Optional ByVal Location As String = "None")
Palo Alto,CA")
End If
End Sub
If flag=false
Dim x as Integer
x=100
System.Console.WriteLine(x)
End if
• Decision constructs are used to represent conditions and the actions to be taken based
on the outcomes of the conditions. 74
If <condition1> [Then]
Statement1
End if
Example: If answer=―yes‖ Then
System.Console.WriteLine(―Answer is yes‖)
End if
The Else clause is used to perform action(s) if the condition evaluates to False.
If <condition1> [Then]
Statement1
Else
Statement3
End if
Example: If sale =―On‖ Then
Discount=5
Else
Discount=0
End if 75
Demonstrating Else
There may be situations where more than one action statements need to be performed
depending on the outcome of the condition.
Module Module1
Sub Main( )
Dim age as Integer
age=System.Console.Readline()
If age>=21
System.Console.WriteLine("The user is an adult")
Else
System.Console.WriteLine("The user is a minor")
End If
End Sub
End Module
If..Elseif..End if Syntax
If <condition1> [Then]
Statement1
[[ElseIf <condition2> [Then]
76
[Statement2] ]
[Else
[Statement3]]
End if
Example:
Module Module1
Sub Main( )
Dim grade as Char
grade= System.Console.ReadLine()
If grade="A"
System.Console.WriteLine("Commission=2000")
Elseif grade="B"
System.Console.WriteLine("Commission=1000")
Else
System.Console.WriteLine("Commission=500")
End If
End Sub
End Module
Nested If Statements
If gender=‖m‖
If age > 18
System.Console.WriteLine(―Admission granted‖)
Else
System.Console.WriteLine(―Admission not
granted..too young!‖)
End If
Else
System.Console.WriteLine(―Admission denied‖)
End If
77
3.12.3 Select..End Select
• Select Case…End Select is used when there are too many conditions to be evaluated.
• The Select Case statement is followed by an expression that must evaluate to one of
the following types:
Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, Short, Single ,String
Syntax:
Select Case <expression>
Case value1
Statement1
...
...
Case valuen
Statementn
[Case Else
Statement]
End Select
Example:
Module Module1
Sub Main( )
Dim n as Integer
System.Console.WriteLine(―Enter a day of the week in numbers‖)
n=System.Console.Readline()
Select case n
Case 1
System.Console.WriteLine("Monday")
Case 2
System.Console.WriteLine("Tuesday")
Case 3
System.Console.WriteLine("Wednesday") 78
Case 4
System.Console.WriteLine("Thursday")
Case 5
System.Console.WriteLine("Friday")
Case 6
System.Console.WriteLine("Saturday")
Case 0
System.Console.WriteLine("Sunday")
End Select
End Sub
End Module
Short circuiting
Short circuiting is determining the outcome of a Multiple-condition if statement without
evaluating each of the If conditions separately. 79
For example, If age>25 AND marital_status=―Y‖
Additional operators provided by VB.NET are AndAlso and OrElse.
Using OrElse Operator
Module Module1
Sub Main( )
Dim salary as Integer
Dim grade as char
salary=System.Console.ReadLine()
grade=System.Console.ReadLine()
If salary>5000 OrElse grade ="A"
System.Console.WriteLine("Additional perks granted")
Else
System.Console.WriteLine("Additional perks not granted")
End If
End Sub
End Module
3.13.2 Do Loop
Do [While | Until condition]
Statement(s)
Loop [While|Until <condition>]
This loop construct is similar to the While..End construct. If the condition evaluates to True,
then the loop statements are executed until the condition becomes False.
A Do..While loop executes as long as the condition or expression evaluates to True. On the
other hand, a Do....Until loop executes as long as condition evaluates to False.
Do System.Console.WriteLine(x)
x=x+1
Loop While x<10
End sub
End Module
Exit statement
Module Module1
Sub Main( )
Dim i as Integer
i=10
while i<100
System.Console.WriteLine(i)
if i mod 7=0
Exit while
End If
i=i+1
End While
End Sub
End Module
For i=1 to 5
For j=1 to 3
System.Console.WriteLine("i is "& i & " j is " & j)
If ((i+j)>4)
Exit for
End if
83
Next j
System.Console.WriteLine("end")
Next i
System.Console.WriteLine ("the end")
End Sub
End Module
InputBox and MsgBox are two useful functions. Each opens a dialog window, which closes
when the user responds. The InputBox is used to get input from the user and MsgBox is used
for output. These our illustrated in this simple message program. The following is its listing:
MsgBox("Thanks, " & strName & ". I have been waiting weeks for someone to do that.")
End Sub
In this example, the InputBox function has one argument, a string that is used to prompt the
user. The function returns whatever the user enters. (If the user clicks on the cancel button, a
string of length zero is returned).
The MsgBox function also has one argument in this example. It is a string to be displayed in
the message box.
The InputBox function requires at least one argument (the prompt), but it has 4 optional
arguments. The optional arguments are a title (string), a default input value (string), and X
and Y coordinates (numeric) that determine the position of the input window on the screen.
strUserIn = InputBox("This is the prompt", "This is the title", "This is the default input", 1, 1)
produces this InputBox in the upper left corner (1, 1) of the screen:
84
Similarly, the MsgBox function requires one argument, a string with the message, but has 2
optional arguments, a numeric code that indicates which buttons to display on the message
box and a string title for the message box.
The button code is most interesting. Using it, you can put OK, Cancel, Retry, and other
buttons on the message box, The following are some of the allowable button code values:
0 OK (the default)
1 OK and Cancel
4 Yes and No
Dim intButton As Integer intButton = MsgBox("This is the message", 3, "This is the title")
85
If there are multiple buttons on a message box, the programmer might also want to know
which one the user clicked. The following table shows the values the MsgBox function can
return:
OK 1
Cancel 2
Abort 3
Retry 4
Cancel 5
Yes 6
No 7
Conclusion
In this unit we learnt about variables, constants, data types and enum list. Also in this unit we
can cover procedures and how to call the procedure, followed by scope of variables and
function mechanism. In the last we can cover lot of programming examples of each topics
mentioned in the syllabus.
2. The data data type in visual basic .net equivalent to ……………… data type in .net FCL.
A) System.Date
B) System.DateTime
C) System.Time
D) System.DateFormat
3. ………………… are symbols used to perform operations; like +, which performs addition
operations, -, which performs subtraction operations and so on.
A) Keywords
B) Operators 86
C) Variables
D) Expressions
4. ……………… are symbolic names given to values stored in memory and declared with the Dim
keyword.
A) Keywords
B) Operators
C) Variables
D) Expressions
5. The keyword ……………………, gives variables protected access, which means they are
accessible only from within their own class.
A) Protected
B) Friend
C) Protected Friend
D) Private
6. The variables in ………………. access means they are accessible only from within their
declaration context, including any nested procedures.
A) Protected
B) Friend
C) Protected Friend
D) Private
7. The …………….. variable is not associated with a specific instance of a class or structure.
A) Protected
B) Shared
C) Shadows
D) Friend
8. The ……………… variable are accessible from within the program that contains their
declaration, as well as anywhere else in the same assembly.
A) Protected
B) Friend
C) Protected Friend
D) Private
9. …………….. is used to declare arrays; which gives upper sounds of the dimensions of an array
variable.
A) bound
B) bound array
C) bound list
D) bound table
13. Which of the following string handling functions and methods are used to compare two strings.
i) StrComp ii) String.Compare iii) String.Equals iv) String.CompareTo
A) i, ii and iii only
B) ii, iii and iv only
C) i, iii and iv only
D) All i, ii, iii and iv
14. The string handling function, ―Mid‖ in visual basic .net is used to ……………..
i) get a substring ii) insert a substring iii) remove text iv) format string
A) i and ii
B) ii and iii
C) iii and iv
D) i and iii
15. The …………… property in array class of vb .net, returns an integer indicating the number of
dimensions of the array.
A) sort
B) reverse
C) rank
D) index of
16. State the following statements are True or False for arrays in visual basic .net are
i) Array are objects in vb .net
ii) Array variables can have the public, protected, friend, private or protected friend specifier
A) True, False
B) False, True
C) True, True
D) False, False
17. In Int32structure ……………….. function converts the string representation of a number of its
Int32 equivalent.
A) parse
B) reverse
C) rank
D) index of
18. ………………. method converts the value of the instance to a double representing the OLE
Automation date.
A) Date CONV
B) TO OA Date 88
C) OLE Date
D) Auto Date
19. What Is COM?
1. Write a program to generate a telephone bill. The conditions for the bill generation are
–
2. What is the difference between an error and an exception? Explain the error handling
mechanism in FEDT?
3. Difference between data adaptor and data reader with the help of suitable example?
4. What is procedure? Explain different types of procedures in visual basic .NET. write a
procedure to find area, circumference of a circle.
5. What are enumerations and dynamic array. Explain with help of examples.
6. What is difference between VB and VB.NET in terms of their features and
application.
3. . NET Programming for Beginners Learn ASP .NET Core in a day easily for
Dummies Engr. Michael David
D) References
1. https://www.amazon.com/Programming-Microsoft-Visual-Basic-
NET/dp/0619016612?tag=uuid10-20.
2. https://dotnet.microsoft.com/learn/dotnet/architecture-guides
3. https://www.c-sharpcorner.com/ebooks/
4. https://bookauthority.org/books/beginner-net-books
5. https://www.quora.com/What-are-the-best-books-for-dot-net-developers
90
Chapter 4: GUI Programming and Object Oriented Features
Learning Outcomes of the Chapter:
GUI you usually use a Toolkit and must follow the pattern of program design laid down by
the toolkit vendor. Each new toolkit will have its own API and set of design rules. GUI
applications tend to consist of a hierarchy of controls. The top level Frame comprising the
application window will contain sub frames which in turn contain still more frames or
controls. A graphical user interface (GUI) allows a user to interact with a computer
program using a pointing device that manipulates small pictures on a computer screen. The
small pictures are called icons or widgets.
We refer to programs that use a graphical user interface as ―GUI programs.‖ A GUI
program is very different from a program that uses a command line interface which receives
user input from typed characters on a keyboard. Typically programs that use a command line
interface perform a series of tasks in a predetermined order and then terminate. However, a
GUI program creates the icons and widgets that are displayed to a user and then it simply
waits for the user to interact with them. This means a GUI program must keep track of the
―state‖ of its processing and respond correctly to user commands that are given in any order
the user chooses. This style of programming is called ―event driven programming.‖ In fact,
by definition, all GUI programs are event-driven programs.
GUI programming has its own set of programming terms. The most common terms are
described below:
Window: An area of the screen controlled by an application. Windows are usually rectangular
but some GUI environments permit other shapes. Windows can contain other windows and
frequently every single GUI control is treated as a window in its own right.
Control: A control is a GUI object used for controlling the application. Controls have
properties and usually generate events. Normally controls correspond to application level
objects and the events are coupled to methods of the corresponding object such that when an
event occurs the object executes one of its methods. The GUI environment usually provides a
mechanism for binding events to methods. 91
4.2 Windows Forms
VB.Net programmers have made extensive use of forms to build user interfaces. Each time
you create a Windows application, Visual Studio will display a default blank form, onto
which you can drag and drop controls from the Visual Studio Toolbox window.
You can change project name instead of WindowsApplication1 in the bottom of dialog box
and click OK button. The following picture shows how to create a new Form in Visual
Studio.
92
Select project type from New project dialog Box:
When you add a Windows Form to your project, many of the forms properties are set by
default, you can change form properties through property window.
An object is a type of user interface element you create on a Visual Basic form by using a 93
toolbox control. In fact, in Visual Basic, the form itself is an object. Every Visual Basic
control consists of three important elements −
■ Properties which describe the object,
4.3.1 PROPERTIES
■ All the Visual Basic Objects can be moved, resized or customized by setting their
properties. A property is a value or characteristic held by a Visual Basic object, such
as Caption or Fore Color.
■ Properties can be set at design time by using the Properties window or at run time by
using statements in the program code.
■ If you are using a control such as one of those provided by the Toolbox, you can call
any of its public methods. The requirements of such a method depend on the class
being used.
■ If none of the existing methods can perform your desired task, you can add a method
to a class.
For example, the MessageBox control has a method named Show
An event is a signal that informs an application that something important has occurred. For
example, when a user clicks a control on a form, the form can raise a Click event and call a
procedure that handles the event. There are various types of events associated with a Form
like click, double click, close, load, resize, etc.
1 Forms The container for all the controls that make up the user
interface.
Labels
Buttons
Text boxes
Menus
Option buttons
95
Check boxes
Abstraction:
System.Windows.Forms.Label
System.Windows.Forms.TextBox
System.Windows.Forms.Button
96
Naming conventions
Text box controls allow entering text on a form at runtime. By default, it takes a single
line of text, however, you can make it accept multiple texts and even add scroll bars to it.
Basic properties: 97
– Text: denotes the entire contents of text box (a string)
– Modified: has text been modified by user? (True / False)
– ReadOnly: set if you want user to view text, but not modify
S. Property Description
No:
2. CharacterCasing Gets or sets whether the TextBox control modifies the case of
characters as they are typed.
3. Font Gets or sets the font of the text displayed by the control.
98
Methods of the TextBox Control
5. Paste Replaces the current selection in the text box with the
contents of the Clipboard.
6. Paste(String) Sets the selected text to the specified text without clearing
the undo buffer.
Interesting events:
The Label control represents a standard Windows label. It is generally used to display some
informative text on the GUI which is not changed during runtime
3. Font Gets or sets the font of the text displayed by the control.
S. Method Description
No:
1. GetPreferredSize Retrieves the size of a rectangular area into which a control can be
fitted.
2. Refresh Forces the control to invalidate its client area and immediately redraw
itself and any child controls.
4.7 BUTTON
The Button control represents a standard Windows button. It is generally used to generate
a Click event by providing a handler for the Click event. 10
1
Properties of the Button
1. AutoSizeMode Gets or sets the mode by which the Button automatically resizes
itself.
7. TabIndex Gets or sets the tab order of the control within its container.
1. GetPreferredSize Retrieves the size of a rectangular area into which a control can
be fitted.
2. NotifyDefault Notifies the Button whether it is the default button so that it can
adjust its appearance accordingly.
2. Double Click Occurs when the user double-clicks the Button control.
10
3
private Sub cmdAdd_Click(...)
Dim i, j, k As Integer
i = System.Convert.ToInt32( this.txtNum1.Text )
j = System.Convert.ToInt32( this.txtNum2.Text )
k = i + j;
End Sub
4.8 List Box : The ListBox represents a Windows control to display a list of items to a user. A user can select an
item from the list. It allows the programmer to add items at design time by using the properties window or at the
runtime.
list of strings
10
4
PROPERTIES OF LISTBOX
1 AllowSelection Gets a value indicating whether the ListBox currently enables selection
of list items.
2 BorderStyle Gets or sets the type of border drawn around the list box.
7 MultiColumn Gets or sets a value indicating whether the list box supports multiple
columns.
8 ScrollAlwaysVisible Gets or sets a value indicating whether the vertical scroll bar is shown
at all times.
9 SelectedIndex Gets or sets the zero-based index of the currently selected item in a list
box.
10 SelectedIndices Gets a collection that contains the zero-based indexes of all currently
selected items in the list box.
11 SelectedItem Gets or sets the currently selected item in the list box.
12 SelectedItems Gets a collection containing the currently selected items in the list box.
13 SelectedValue Gets or sets the value of the member property specified by the
ValueMember property.
14 SelectionMode Gets or sets the method in which items are selected in the list box. This
property has values −
None
One
MultiSimple
MultiExtended
10
5
15 Sorted Gets or sets a value indicating whether the items in the list box are
sorted alphabetically.
16 Text Gets or searches for the text of the currently selected item in the list
box.
17 TopIndex Gets or sets the index of the first visible item of a list box.
1 BeginUpdate Prevents the control from drawing until the EndUpdate method
is called, while items are added to the ListBox one at a time.
3 EndUpdate Resumes drawing of a list box after it was turned off by the
BeginUpdate method.
4 FindString Finds the first item in the ListBox that starts with the string
specified as an argument.
5 FindStringExact Finds the first item in the ListBox that exactly matches the
specified string.
The ComboBox control is used to display a drop-down list of various items. It is a combination of a text box
in which the user enters an item and a drop-down list from which the user selects an item
Properties of ComboBox
1. AllowSelection Gets a value indicating whether the list enables selection of list items.
10
7
2. AutoComplete Gets or sets an option that controls how automatic completion works
for the ComboBox.
4. DropDownHeight Gets or sets the height in pixels of the drop-down portion of the
ComboBox.
5. DropDownStyle Gets or sets a value specifying the style of the combo box.
6. DropDownWidth Gets or sets the width of the of the drop-down portion of a combo
box.
7. DroppedDown Gets or sets a value indicating whether the combo box is displaying
its drop-down portion.
10. Items Gets an object representing the collection of the items contained in
this ComboBox.
11. MaxDropDownItems Gets or sets the maximum number of items to be displayed in the
drop-down part of the combo box.
12. MaxLength Gets or sets the maximum number of characters a user can enter in
the editable area of the combo box.
13. SelectedIndex Gets or sets the index specifying the currently selected item.
15. SelectedText Gets or sets the text that is selected in the editable portion of a
ComboBox.
16. SelectedValue Gets or sets the value of the member property specified by the
ValueMember property.
17. SelectionLength Gets or sets the number of characters selected in the editable portion
of the combo box.
18. SelectionStart Gets or sets the starting index of text selected in the combo box.
19. Sorted Gets or sets a value indicating whether the items in the combo box
are sorted. 10
8
20. Text Gets or sets the text associated with this control.
1. BeginUpdate Prevents the control from drawing until the EndUpdate method is
called, while items are added to the combo box one at a time.
2. EndUpdate Resumes drawing of a combo box, after it was turned off by the
BeginUpdate method.
3. FindString Finds the first item in the combo box that starts with the string specified
as an argument.
4. FindStringExact Finds the first item in the combo box that exactly matches the specified
string.
5. SelectAll Selects all the text in the editable area of the combo box.
i = Type.SelectedIndex
End If
End Sub
Dim i As Integer
i = Sizep.SelectedIndex
End If
End Sub
Dim i As Integer
i = Toppings.SelectedIndex
Next
End Sub 11
0
Difference between ComboBox and ListBox
COMBOBOX LISTBOX
Can select only one option from the list. Can select more than one options from the list.
We can add, select, edit info at the run time. We can‘t add, select, edit info at the run time.
Only drop down facility available Both drop up and drop down facility available.
Checkbox can‘t be used within combobox. Checkbox can be used within listbox.
Occupies less space but shows only one value for Occupies more space but shows more than one
visibility. value.
• The Image property of the control allows you to set an image both at design time or at run time.
11
1
Properties of the PictureBox
AllowDrop
Specifies whether the picture box accepts data that a user drags on it.
ErrorImage
Gets or specifies an image to be displayed when an error occurs during the image-loading process or if the image
load is cancelled
ImageLocation
Gets or sets the path or the URL for the image displayed in the control.
Text
SizeMode
Determines the size of the image to be displayed in the control. This property has following values −
Normal − the upper left corner of the image is placed at upper left part of the picture box
AutoSize − allows resizing the picture box to the size of the image 11
2
CenterImage − allows centering the image in the picture box
Zoom − allows increasing or decreasing the image size to maintain the size ratio.
ToString
KeyPress: Occurs when a key is pressed when the control has focus.
ForeColorChanged
Resize
SizeChanged
• TextChanged
• Leave
• RightToLeftChanged
11
3
4.11 CHECK BOX
• The CheckBox control allows the user to set true/false or yes/no type options.
Appearance
AutoCheck
Gets or sets a value indicating whether the Checked or CheckedState value and the appearance of the control
automatically change when the check box is selected.
CheckAlign
Gets or sets the horizontal and vertical alignment of the check mark on the check box.
CheckState
• Text
• ThreeState
Gets or sets a value indicating whether or not a check box should allow three check states rather than two.
METHODS OF CHECKBOX
OnCheckedChanged
OnClick
EVENTS OF CHECKBOX
AppearanceChanged
Occurs when the value of the Appearance property of the check box is changed.
CheckedChanged
Occurs when the value of the Checked property of the CheckBox control is changed.
CheckStateChanged
Occurs when the value of the CheckState property of the CheckBox control is changed.
11
6
4.12 RADIO BUTTONS
• If you need to place more than one group of radio buttons in the same form, you should place them in
different container controls like a GroupBox control.
11
7
PROPERTIES OF RADIO BUTTON
Appearance
AutoCheck
Gets or sets a value indicating whether the Checked value and the appearance of the control automatically
change when the control is clicked.
CheckAlign
Gets or sets the location of the check box portion of the radio button.
Text
Checked
PerformClick
AppearanceChanged
Occurs when the value of the Appearance property of the RadioButton control is changed.
CheckedChanged
Occurs when the value of the Checked property of the RadioButton control is changed.
11
8
11
9
4.13 PANEL
A Panel is a control that contains other controls/elements like Label, Buttons. It controls the appearance and
visibility of the controls it contains.
12
You can use a Panel to group collections of controls such as a group of Radio Button controls.
0
Properties of panel
12
1
Panels can be used to create multiple pages in a single form
The ScrollBar controls display vertical and horizontal scroll bars on the form.
There are two types of scroll bar controls: HScrollBar for horizontal scroll bars and VScrollBar for
vertical scroll bars. 12
2
Properties of scroll bar
12
3
Events of scroll bar
12
4
4.15 Timer
Timer is a function that Generates an event after a set interval, with an option to generate recurring events
The Timer component is a server-based timer that raises an Elapsed event in your application after the
number of milliseconds in the Interval property has elapsed.
You can configure the Timer object to raise the event just once or repeatedly using
the AutoReset property.
The System.Timers.Timer class has the same resolution as the system clock. This means that the Elapsed
event will fire at an interval defined by the resolution of the system clock if the Interval property is less
than the resolution of the system clock.
EVENTS
12
6
The ListView control is used to display a list of items. Along with the TreeView control, it allows you to create a
Windows Explorer like interface.The ListView control displays a list of items along with icons. The Item
property of the ListView control allows you to add and remove items from it. TheSelectedItem property contains
a collection of the selected items. TheMultiSelect property allows you to set select more than one item in the list
view. The CheckBoxes property allows you to set check boxes next to the items.
Properties of ListView
1)Alignment
2)AutoArrange
3)BackColor
4)CheckBoxes
Gets or sets a value indicating whether a check box appears next to each item in the control.
5)CheckedItems
6)Columns
Gets the collection of all column headers that appear in the control.
7)Items
8)Sorting
9)SelectedItems
10)CheckedIndices
11)SelectedIndices
1)Clear
2)To String
Events
1)ColumnClick
2)ItemCheck
3)SelectedIndexChanged
4)TextChanged
Example
Me.Controls.Add(ListView1)
ListView1.View = View.SmallIcon
End Sub
End Class
12
9
4.17 TreeView Control
The TreeView control is used to display hierarchical representations of items similar to the ways the files and
folders are displayed in the left pane of the Windows Explorer. Each node may contain one or more child nodes.
Properties
1)BackColor
2)BackgroundImage
3)BorderStyle
4)CheckBoxes
Gets or sets a value indicating whether check boxes are displayed next to the tree nodes in the tree view control.
5)Font
The current foreground color for this control, which is the color the control uses to draw its text.
7)Nodes
Gets the collection of tree nodes that are assigned to the tree view control.
8)SelectedNode
Gets or sets the tree node that is currently selected in the tree view control.
9)Sorted
Gets or sets a value indicating whether the tree nodes in the tree view are sorted.
10)Text
11)VisibleCount
Gets the number of tree nodes that can be fully visible in the tree view control.
Methods
1)CollapseAll
Collapses all the nodes including all child nodes in the tree view control.
2)ExpandAll
3)GetNodeAt
4)GetNodeCount
5)Sort
6)ToString
13
1
Events
6)NodeMouseClick: Occurs when the user clicks a TreeNode with the mouse.
TreeNode Class
The TreeNode class represents a node of a TreeView. Each node in a TreeView control is an object of the
TreeNode class. To be able to use a TreeView control we need to have a look at some commonly used properties
and methods of the TreeNode class.
Properties
2)Checked: Gets or sets a value indicating whether the tree node is in a checked state.
3)FirstNode: Gets the first child tree node in the tree node collection.
4)Index: Gets the position of the tree node in the tree node collection.
5)IsSelected: Gets a value indicating whether the tree node is in the selected state.
6)IsVisible: Gets a value indicating whether the tree node is visible or partially visible.
10)Parent: Gets the parent tree node of the current tree node.
11)TreeView: Gets the parent tree view that the tree node is assigned to.
12)Text: Gets or sets the text displayed in the label of the tree node.
13
2
Methods
4)Remove: Removes the current tree node from the tree view control.
Example
Me.Controls.Add(TreeView1)
TreeView1.Nodes.Clear()
TreeView1.Nodes.Add(root)
TreeView1.Nodes(0).Nodes(0).Nodes.Add(New _
Next loopindex
Next loopindex
Me.Text = "tutorialspoint.com"
End Sub
End Class
4.18 Toolbar:
In the graphical user interface ( GUI ) for a computer, a toolbar is a horizontal row or vertical column of
selectable image "buttons" that give the user a constantly visible reminder of and an easy way to select certain
desktop or other application functions
The toolbar is a very popular and much-used addition to a programme. It's difficult to think of a piece of
software that doesn't make use of them. VB.NET lets you add toolbars to your forms, and the process is
quite straightforward. Let's see how it's done:
Either start a new Windows project, or keep the one you currently have. To add a toolbar to the top of your form,
expand the Toolbox and locate the ToolStrip control:
13
4
Double click the ToolStrip control, and it will be added to the top of your form:
You should also notice the ToolStrip object that appears at the bottom of the window:
ToolStrips work by adding buttons and images to them. The button is then clicked, and an action
performed.
Click on your ToolStrip to select it. In the property box for the ToolStrip, you'll notice that it has the
default Name of ToolStrip1. We'll keep this Name. But locate the Items (Collection) property:
13
5
Click the button with the three dots in it. This brings up the Items Collection Editor:
To add a new button to your ToolStrip, click the Add button at the top. The button appears in the
Members box (ToolStripButton1):
Notice that the new button has its own list of properties, just to the right. To add an image to this new
button, locate the Image property:
13
6
Click the small button with the 3 dots in it to bring up the Select Resource box:
In the image above, we've selected "Project resource file", and then clicked the Import button. We then navigated
to some Bitmap images and imported the five that you can see in the screenshot above (these are in the13BITMAP
7
folder that you download at the top of this tutorial). Click OK when you have imported some images. You will
be returned to the Item Collection Editor. Click OK on this, as well. The ToolStrip on your form will then look
like this:
To add a new button to the toolstrip, click on Button from the drop down menu in the image above. A default
button is added called ToolStripButton2. (The first button is called ToolStripButton1.)
To change the picture of the new button, locate the Image property in the properties area bottom right:
Click the button with the three dots in it to bring up the Select Resource dialogue box again. Select
Project resource file from the list, and choose a new icon: 13
8
The default button image will then change to the one you selected:
(If you wanted to, you could change the name of the button. Just delete ToolStripButton2 from
the Name property and type a new one.).
Repeat the steps above to add more buttons to the toolstrip. It should then look something like :
Double click your first ToolStripbutton to bring up the coding window. It should look like this:
13
9
Run your programme and click your ToolStrip button. You should see the message box display. In a real
programme, however, the code would be the same code for a menu item.
A status bar is commonly used to provide hints for the selected item or information about an action
currently being performed on a dialog. Normally, the StatusBar is placed at the bottom of the screen.
StatusBar control is not available in Toolbox of Visual Studio 2010. StatusStrip control replaces
StatusBar in Visual Studio 2010. But for backward compatibility support, StatusBar class is available in
Windows Forms.
StatusBar Properties
StatusBar Events
Name Description
Occurs when a panel that has the OwnerDraw style set needs
DrawItem to be redrawn. You must subscribe to this event if you want
to draw the contents of a panel yourself.
This class contains all the information about the individual panels in the Panels collection. The
information that can be set ranges from simple text and alignment of text to icons to be displayed and the
14
style of the panel.
0
Example For StatusBar
To understanding StatusBar control drag and drop status strip and make text blank and add
2toolstatuslabel and 1 toolstatusprogressbar. And drag 1textbox and 1 button1, timer control and change
property according to your choice.
On clicking button progress bar will show on status strip control until webpage will not open. when web
page is loaded progress bar will not be display and label text will be web address and done that means
page has been loaded as shown below
14
1
4.20 DIALOG CONTROLS
Visual studio contains 8 standard dialog box controls on the dialogs and printing tabs of the toolbox. They are
readymade , so you don‘t need to create your own custom dialog boxes for common tasks like opening, saving,
etc
DIALOG TAB
14
2
PRINTING TAB
Printpreviewdialog- displays print preview dialog box as the word program does.
Pagesetupdialog-lets the user control page setup options, such as margins, paper size , and layout.
Multiple document interface (MDI) applications permit more than one document to be open at a time.
This is in contrast to single document interface (SDI) applications, which can manipulate only one
document at a time. Visual Studio .NET is an example of an MDI application—many source files and
design views can be open at once. In contrast, Notepad is an example of an SDI application—opening a
document closes any previously opened document.
CHARACTERISTICS
Display those multiple form instances such that they appear inside the region of another form
MDI applications consist of a main form, which does not itself display any data, and one or more child
forms, which appear only within the main form and are used for displaying documents. The main form is
called the MDI parent, and the child forms are called the MDI children.
14
3
Add another form, Form2 to this application for this you have to right-clicking on the project name
in Solution Explorer
14
4
Add->Add Windows Form.We will make From1 as the MDI parent window and Form2 as MDI child
window. To make Form1as MDI parent select Form1 and in its Properties Window, set the
property IsMdiContainer toTrue.
Once you set that property to true the Form1 acts like an MDI container for the child forms. It also
changes its color and look like the image
14
5
Now, from the toolbox drag a MenuStrip onto Form1. We will display child windows when a menu item
is clicked. Name the top-level menu item to New with submenu items as New Child Window, Arrange
Child Window and Exit.
14
6
Public Class Form1
Dim ChildF As Integer = 0
Dim ChildForms(6) As Form2
'Declaring an array to store child windows
'Six child windows (Form2) will be displayed
Handles NewToolStripMenuItem.Click
ChildF += 1
ChildForms(ChildF) = New Form2()
ChildForms(ChildF).Text = "ChildForm" & Str(ChildF)
'Setting title for child forms and incrementing the number with an array
ChildForms(ChildF).MdiParent = Me
ChildForms(ChildF).Show()
End Sub
Handles ArrangeChildWindowToolStripMenuItem.Click
Me.LayoutMdi(MdiLayout.Cascade)
'Arranging child windows on the parent form with predefined LayoutMdi method
'Different layouts available are, ArrangeIcons, Cascade, TileHorizontal, TileVertica
End Sub
Menus
Menu Bar
Contains menus which drop down to display list of menu items
Can be used in place of or in addition to buttons to execute a procedure
Menu items are controls with properties and events
Easy to create menus for a Windows form using the Visual Studio environment‘s Menu Designer
14
Menus will look and behave like standard Windows menus 8
Defining Menus
14
9
Click the type here tag, type clock and then press enter.(first menu)
Type date to create a date command for the clock menu ,then press enter.(submenu)
Type time to create a time command for the menu , and then press enter.
Holds the words that appear on the screen – like the Text property of a button or label
To conform Windows standards the first menu‘s Text property should be File, with a keyboard access
key
Use the ampersand (&) in the text to specify the key to use for keyboard access
Enter and change the Text property for each menu and menu item using the Menu Designer or make the
changes in the Text property using the Properties window
15
0
The Name Property
The items are named so well that there won‘t be a need to change the Name property of any menu
component
If the Text property is changed for any menu item, the item is not automatically renamed; it will
need to be renamed
ToolStripMenu Items in the collection can be displayed, reordered, added, deleted using the Items
Collection Editor
Click the clock menu name on the form,pause a moment and then click it again.
You will see it highlighted.go to the left of c of clock and type & to define C as the access key for the
clock menu.
Similarly do it for time and date making T and D their access keys.
Press enter .
15
1
PROCESSING MENU CHOICES
In this,we will add a label object to form to display the ouput of the time and date command on to clock
menu.
ADD LABEL
Click the label control in the toolbox and create a label in the middle of the form.
Click on clock menu and double click the time command.type in code editor- label1.text=timestring.
Again in the clock menu double click the date command and type in the code editor-
label1.text=datestring.
Press enter
15
3
RUN THE MENU BUTTON
Start debugging on standard toolbar. Click clock menu and time button. Current time will display or press
and release alt button and then press C key then T. Similary do it for date command.
Submenus
Filled triangle to the right of the menu item indicates to the user the existence of a submenu
Create submenus by moving to the right of a menu item and typing the next item's text
Separator Bars
To create a separator bar, add a new menu item and click on its drop-down arrow
Place the File menu at left end of menu bar and end File menu with the Exit command
MCQ’S
Q.1 A GUI
D. Both a and b
Q.2 Which is true about the name and text property of a control?
A.The text property changes to match any changes in the name property.
C.They are never the same unless the programmer makes it that way.
D.The name property changes to match any changes in the text property.
Q.3 Which are the standard prefixes for the Button and Combo box controls respectively?
A. Font B. show
C. ForeColor D. BackColor
Q.8 It is a comprehensive, object-oriented collection of reusable types that you can use to develop applications.
A.Class Library
B. Solution Explorer
C. Properties Window
Answers
Q1. D
Q2. B
Q3. C
Q4. D
Q5. B
Q6. B
Q7. D
Q8. A
Q.1 Write a program to change the font properties(Font name, FontSize, FontColor, BackColor) of Label Control
on Click Procedure of Button Control.
Q.2 Write a program to accept 10 integer values from user and display all the odd numbers in listbox. 15
6
Q.3 Explain the following control along with 4 commonly used properties or methods of each control:-
ComboBox, RadioButton, Button, Timer, PictureBox.
Learners are expected to engage with any two of the following or such similar activities
Assignment 1
Assignment 2
Q.2 Write a program to change the font properties(Font name, FontSize, FontColor, BackColor) of
15
7
Chapter 5: Object Oriented Features:
Learning Outcomes of the Chapter:
Visual Basic is Object-Oriented Programming Language. Visual Basic .NET supports all features of
OOP like
Object Oriented Programming (OOP) is based on a real world interpretation of programming elements.
Abstraction refers to the act of representing essential features without including the background
details or explanation.
Encapsulation refers to the wrapping up of data & operations/functions(that operate on the data)
Into a single unit(called class)
Advantages of OOP
Re-use of code.
Ease of comprehension.
Disadvantages of OOP
A class is a way to bind the data describing an entity & its associated functions together.
...
...
End Class
• Object Oriented Programming (OOP) is based on a real world interpretation of programming elements.
Advantages of OOP
• Code reuse.
• Users of objects do not need to know the internal specifications of the object.
• Objects can also be made to exhibit varying behaviour under different situations without changing any of
the functionality.
car.companyname="Ford"
car.make="Ikon"
End sub
Object
Properties:--denote read-only values that once set cannot be changed and values that can be read as well as
changed.
Using Properties
...
...
agevalue=value
End Set
Get
Return agevalue
End Get
End Property
16
... 0
End Class
Demonstrating Properties
Module m
age=value
End Set
Get
Return age
End Get
End property
End class
student.name="Jeremy"
student.gender="M"
student.agevalue=19
System.Console.WriteLine(student.name)
16
1
System.Console.WriteLine(student.gender)
System.Console.WriteLine(student.agevalue)
End sub
End module
Types of Properties
WriteOnly Properties
ReadOnly Properties
ReadWrite Properties
Using Methods
Module m
Public X as Integer
Public Y as Integer
x=System.Console.ReadLine( )
y=System.Console.ReadLine( )
End Sub
End Class
P.Assign( )
System.Console.WriteLine("Point p is")
16
2
System.Console.WriteLine(p.x)
System.Console.WriteLine(p.y)
End Sub
End Module
Module m
age=value
End Set
Get
Return age
End Get
End property
name=System.Console.ReadLine()
gender=System.Console.ReadLine()
address=System.Console.ReadLine()
16
3
End Sub
End Class
student.agevalue=19
student.input()
System.Console.WriteLine()
System.Console.WriteLine()
System.Console.WriteLine(student.name)
System.Console.WriteLine (student.gender)
System.Console.WriteLine (student.agevalue)
System.Console.WriteLine (student.address)
End Sub
End Module
A constructor is a method having the same name as the class within which it is defined and executes
automatically every time an object is created.
Destructors are methods that execute whenever the object goes out of scope or is destroyed.
Module m
Public X as Integer
Public Y as Integer
16
4
Public Sub New()
System.Console.WriteLine("This is a constructor")
x=System.Console.ReadLine()
y=System.Console.ReadLine()
End sub
End class
System.Console.WriteLine("Point p is")
System.Console.WriteLine(p.x)
System.Console.WriteLine(p.y)
End sub
End module
Destructors
• Normally used for cleanup operations such as releasing or freeing of memory that is no longer
required.
...
...
End sub
16
5
Module m
Public X as Integer
Public Y as Integer
System.Console.WriteLine("This is a constructor")
x=System.Console.ReadLine()
y=System.Console.ReadLine()
End Sub
End sub
End class
System.Console.WriteLine("Point p is")
System.Console.WriteLine(p.x)
System.Console.WriteLine(p.y)
End Sub
End Module
16
6
5.5 Overloading
• Overloading is the process of declaring methods of a class having the same name but different
signatures.
• In VB.NET, functions, procedures, constructors and properties within a class can be overloaded
provided they satisfy the prerequisites for overloading.
• Names of parameters
• Return types
• Overloading refers to an item being used in more than one way. Operator names are often
overloaded. For instance, the plus sign (+) refers to addition of integers, addition of singles, addition
of doubles, and concatenation of strings. Thus, the plus symbol (+) is overloaded. It‘s a good thing,
too; otherwise, we would need separate symbols for adding integers, singles, and doubles.
• Function names can also be overloaded. For instance, the absolute value function, Abs, can take an
integer parameter, a single parameter, or a double parameter. Because the name Abs represents
several different functions, it is overloaded. In fact, if you look at the documentation for the Abs
member of the Math class (in the System namespace of the Framework Class Library), you will find
the following declarations
EXAMPLE
• In the above example there are two method which has the same name but use for different purpose
one define the area of circle and other define the area of rectangle. Both method have the different
parameter.
16
7
Demonstrating Overloading
Module m
Class X
Dim c as Integer
c=a+b
End Sub
Dim s3 as String
s3=s1+s2
End Sub
End Class
Sub Main()
Y.Max(50,100)
End Sub
End Module
Overloading Constructors
Module M
Class Base
16
8
System.Console.WriteLine("Parameterless constructor")
End Sub
End Sub
End Sub
End Class
Sub Main()
End Sub
End Module
Overloading Properties
Module m
Public Class X
addr=add
End Set
16
9
Get
Return addr
End Get
End property
addr2=add
End Set
Get
Return addr2
End Get
End property
End class
Dim s as string
Y.address()=System.Console.ReadLine()
Y.address("residence")=System.Console.ReadLine()
System.Console.WriteLine(Y.address("residence"))
System.Console.WriteLine(Y.address())
End Sub
17
0
End Module
Inheritance
Module m
End Class
Inherits Building
Public Name
End class
End sub
End module
5.6 Overriding
• Overriding is the process of overwriting the methods or properties of a base class in a derived class.
The base class method must be marked with the keyword Overridable and the derived class method must be
marked with the keyword Overrides.
Module m
Class Base
End Sub
17
1
End Class
Class Child
Inherits Base
End Sub
End Class
Sub Main()
B.Test(10,20)
C.Test(10,20)
End Sub
End Module
• Abstract elements in classes that bear the MustInherit keyword are marked with the MustOverride
keyword to indicate that they are to be implemented by the derived class.
To hide an inherited method within a derived class, and invoke an overridden version of the method,
we use the Shadows keyword.
Demonstrating Shadows
Module m
Class Base
End Sub
17
2
End Sub
End Class
Class Child
Inherits Base
End sub
End Class
Sub Main
‗invalid
'C.Test()
'valid
‗called here
End Sub
End Module
MyBase:--Refers to base class method in a derived class that has overridden methods of the base class.
Module M1
System.Console.WriteLine("Eats Food")
End sub
End Class
17
3
Public Class Cow
Inherits Animal
System.Console.WriteLine("Eats grass")
End sub
MyBase.Eats()
End Sub
End class
Demonstrating MyBase
Module M1
System.Console.WriteLine("Eats Food")
End sub
End Class
Inherits Animal
System.Console.WriteLine("Eats grass")
End sub
MyBase.Eats()
17
4
End Sub
End class
Sub Main()
C.Eating()
C.Eats()
End Sub
End Module
Later, if we wish to call the base class version, then we must use the MyClass keyword.
Module M1
End sub
Eats()
MyClass.Eats()
End Sub
End Class
17
5
Inherits Animal
End sub
End class
Sub Main()
C.Eats()
C.Eatinghabits()
End Sub
End Module
Protected Elements may be used within the derived class but not outside the
derived class
Protected Friend Element bears features of both Protected and Friend modifiers.
Access modifiers
Public : Elements are available throughout the current project and within other projects that are
referencing the current project.
Module n
Sub Main( )
System.Console.WriteLine("first call")
print1( )
System.Console.WriteLine("second call")
print1( )
System.Console.WriteLine("third call")
print1( )
End Sub
Sub print1( )
Static i as Integer
i=i+1
System.Console.WriteLine(i)
End Sub
End module
Module m
Public Class X
Public J as Integer
Private K as Integer
Protected L as Integer
17
7
Friend M as Integer
L=100
End sub
End class
Public Class Y
Inherits X
Public N as Integer
End class
A.J=100
A.M=100
A.Test()
B.J=100
B.M=100
B.Test()
B.N=100
End Sub
End Module
5.8 Inheritence
Modularity is the property of a system that has been decomposed into set of cohesive and
loosely coupled modules.
17
8
Inheritance is the capability of one class of things to derive capabilities or properties from
another class.
Inheriting Constructors
Module m
Class Base
End Sub
End Class
Class Child
Inherits Base
End Class
Sub Main()
End Sub
End Module
Module m
Class Base
End Sub
End Sub
End Class
Class Child
Inherits Base
End Class
Sub Main()
End Sub
End Module
Final classes :--A final class is a class that cannot be used as a base class.
Module m
End Sub
End Class
Class Child
18
0
Inherits AbsBase
End sub
End Class
Sub Main()
C.Test()
C.AnotherTest()
End Sub
End Module
Demonstrating NotInheritable
Module m
NotInheritable Class One
Public Sub Test()
End Sub
Public Sub Test(X as Integer)
End Sub
End Class
'Invalid Class Child Inherits One
Sub Main
Dim F as new One()
F.Test()
F.Test(100)
End Sub
End Module
18
1
5.10 Interface
Defining an Interface:--
Interface <name>
...
...
End Interface
Implementing an Interface:--
Class <classname>
Implements<interfacename>
...
...
End Class
or
Class <classname>
Implements<interfacename>
...
...
End Class
Module M
18
2
Public Interface I
Sub First()
Sub Second()
End Interface
Public Class X
Implements I
System.Console.WriteLine("Implementation of first
method")
End sub
System.Console.WriteLine(―Implementation of second
method‖)
End Sub
End Class
Y.First()
Y.Second()
End Sub
End module
Module M
Public Interface I
18
3
Sub Test()
End Interface
Public Class T
System.Console.WriteLine("Method Testing")
End Sub
End Class
Public Class X
Inherits T
Implements I
System.Console.WriteLine("Implemented method")
End sub
End Class
Y.Test()
Y.Testing()
End Sub
End module
5.11 Namespaces:
Namespaces are used to organize nested entities such as other namespaces, classes, interfaces and so on.
System is one of the most commonly used
namespaces in VB.NET
...
End Namespace
Creating a Namespace
Namespace Plants
System.Console.WriteLine(flowering)
End sub
End Class
End Namespace
Using a Namespace
Module M1
Sub Main()
s.flowering=true
s.print()
End Sub
End Module
Imports Plants
Module M1
Sub Main()
18
5
Dim s as New Shrub
s.flowering=true
s.print()
End Sub
End Module
Conclusion : In this Unit Students are familiar with Object Oriented Features: Classes and Objects, Access
Specifiers: Private, Public and Protected, Building Classes, Reusability, Constructors, Inheritance, Overloading,
Overriding, creation and use of Namespaces.
MCQ’S
C. programs D. objects
Q.3 _________ are interactive objects that you place in dialog boxes or other windows to carry out user actions.
A. Forms B. Controls
C. Classes D. Objects
Q.4 The _________________ enable us to pass data between a program and a class.
A. Properties B. Procedures
C. Variables D. Functions
Q.5 Which of the following accesss modifier specifies that a property or procedure overrides an identically named
property or procedure inherited from a base class?
18
6
A. Overrides B. Overridable
C. ParamArray D. Partial
Q.6 Which of the following accesss modifier specifies that a property or procedure cannot be overridden in a derived
class?
A. NotOverridable B. Optional
C. Out D. Overloads
Answers
Q9. B
Q10. A
Q11. B
Q12. A
Q13. A
Q14. A
Q15. C
Q.1 Explain the concept of Overriding, Overloading, MustInherit, Shadow with example in context with
Classes in Visual Basic.NET.
Q.2 Explain the concept of Object Oriented programming in VB.NET and Explain how to define a Class
and perform inheritance in VB.NET.
Q.4 Create function for Factorial/ Prime No/ List of odd and Even no
18
7
E) Suggested Skill Development Projects/Assignments
Students can create a working project on Result Management System, Library Management, Students
Information Management and Event Management System using the skills learned in this curriculum.
Learners are expected to engage with any two of the following or such similar activities
Assignment 1:
Q1. Explain enumeration with the help of example
Q2. Explain Procedure calling by using Optional Argument and Paramarray argument
Q3. Explain Arrays/Multi dimensional Arrays/Dynamic Array
Q4. Differentiate Classes and Structure with example
Assignment 2:
Q1.Explain five methods of Array Class with example
Q2.Explain Overriding, Overloading, MustInherit, MustOverride, Not Overridable and Shadow with
example
Q3.Explain For, While, do while and For each loop with the help of example
Q4.Explain Conditional construct of VB.Net
18
8
Chapter 6: Introduction to ADO
Introduction
This chapter basically deals with the ADO and its architecture. It helps in
understanding the difference between ADO and ADO.NET. It enables one to
associate a database with a software application and a summarized data can be
created with the help of Crystal reports.
It works only when data store is It does not needs active connection to
2. connected. access data from data store.
It access and store data from data It access and store data from data source
4. source by recordset object. by dataset object.
18
9
S.No. ADO ADO.NET
The System.Data namespace and its five supporting namespaces define the ADO.NET
functionality. L. These namespaces reside in the System.Data.dll assembly.
Besides these namespaces, each new data provider may have its own namespace. For
example, if you install the Oracle .NET data provider, the installation adds a new
namespace, the Microsoft.Data.OracleClient namespace, which also belongs to
ADO.NET.
The System.Data.Odbc namespaces define Odbc .NET data provider classes to work
with the ODBC data sources. To work with ODBC data sources, you need to install
an ODBC driver for a database. The System.Data.Odbc namespace classes start
with Odbc, followed by the component. For example, the OdbcConnection class
represents a Connection object. Some of the common classes of this namespace
are OdbcDataAdapter, OdbcDataReader, OdbcCommand, OdbcCommandBuilder, O
dbcError, OdbcParameter, OdbcPermission, and OdbcTransaction. To use these
classes in your application, you need to add a reference to
the System.Data.Odbc namespace in your application.
The disconnected components build the basic ADO.NET architecture. We can use
these components (or classes) with or without data providers. For example, you can
use a DataTable object with or without data providers.
Shared or common components are the base classes for data providers and are shared
by all data providers.
The data provider components are specifically designed to work with different kinds
of data sources. For example, Odbc data providers work with ODBC data sources, and
OleDb data providers work with OLE-DB data sources.
Figure 1-4 represents the ADO.NET components model and shows how the components
work together.
Figure 1-5: The relationship between Connection, DataAdpater, and a data source
Figure 1-6: The relationship between the Command object and the Connection object
The Connection object also plays a useful role in creating a transaction. Transactions
are stored in Transaction objects, and Transaction classes have all those nice features
for dealing with transactions such as commit and rollback.
Figure 1-7 shows the relationship between the Connection object and a transaction.
19
3
Figure 1-8: The relationship between DataAdapter and Command
Each data provider has its own Command class. Each data provider has
a Connection class. The OleDbCommand, SqlCommand, and OdbcCommand classes
represent the Command object of the OleDb, Sql, and Odbc data providers,
respectively.
You call the ExecuteReader method of a Command object, which executes the query
and returns data in a DataReader object (see Figure 1-9).
The SQL SELECT command is fairly easy to construct. Even if you don't know how
to construct a SQL SELECT command, the Query Builder in VS helps you. But
notice there are three other commands in Figure 1-8 to construct:
InsertCommand, UpdateCommand, and DeleteCommand.
These commands can get quite complicated in .NET because they require complex
parameter objects and often involve large lists of columns. ADO.NET provides a
nice utility known as the CommandBuilder that automatically builds these
commands for you.
Figure 1-10 describes the relationship
between CommandBuilder and DataAdapter.
CommandBuilder is constructed with DataAdapter and immediately generates the
remaining Command objects.
The DataAdapter object serves as a conduit between the data source and the DataSet.
The DataAdapter knows about the DataSet, and the DataAdapter knows how to
populate the DataSet.
The DataAdapter also knows about the connection to the data source.
Figure 1-11 is a model that shows the simple relationship between the DataAdapter,
a DataSet, and a data source. 19
4
Figure 1-11: The relationship between DataAdapter and DataSet
The Fill method of a DataAdapter fills data from a DataAdapter to the DataSet, and
the UPDATE method makes DataSet changes to the final data source.
There's a DataAdapter available for each data provider.
OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter represent
the DataAdapter classes for OleDb, Sql, and Odbc data providers, respectively.
Connecting to a Database:
The .Net Framework provides two types of Connection classes −
SqlConnection − designed for connecting to Microsoft SQL Server.
OleDbConnection − designed for connecting to a wide range of databases, like
Microsoft Access and Oracle.
Example 1:
We have a table stored in Microsoft SQL Server, named Customers, in a database
named testDB.
Let us connect to this database. Take the following steps −
Select TOOLS → Connect to Database
19
6
Select a server name and the database name in the Add Connection dialog box.
19
Click on the Test Connection button to check if the connection succeeded. 7
Add a DataGridView on the form.
19
8
Choose DataSet as the database model.
19
9
Save the connection string.
Choose the database object, Customers table in our example, and click the Finish
button.
20
0
Select the Preview Data link to see the data in the Results grid −
When the application is run using Start button available at the Microsoft Visual Studio tool
bar, it will show the following window −
20
1
Example 2
In this example, let us access data in a DataGridView control using code. Take the following
steps −
Add a DataGridView control and a button in the form.
Change the text of the button control to 'Fill'.
Double click the button control to add the required code for the Click event of the
button, as shown below −
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
'TODO: This line of code loads data into the 'TestDBDataSet.CUSTOMERS' table.
You can move, or remove it, as needed.
Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
Clicking the Fill button displays the table on the data grid view control −
Clicking the Fill button displays the table on the data grid view control −
20
5
6.10 DATA BINDNG:
Every ASP.NET web form control inherits the DataBind method from its parent
Control class, which gives it an inherent capability to bind data to at least one of its
properties. This is known as simple data binding or inline data binding.
Simple data binding involves attaching any collection (item collection) which
implements the IEnumerable interface, or the DataSet and DataTable classes to the
DataSource property of the control.
On the other hand, some controls can bind records, lists, or columns of data into their
structure through a DataSource control. These controls derive from the
BaseDataBoundControl class. This is called declarative data binding.
The data source controls help the data-bound controls implement functionalities such
as, sorting, paging, and editing data collections.
The BaseDataBoundControl is an abstract class, which is inherited by two more
abstract classes:
DataBoundControl
HierarchicalDataBoundControl
The abstract class DataBoundControl is again inherited by two more abstract classes:
ListControl
CompositeDataBoundControl
The controls capable of simple data binding are derived from the ListControl abstract class
and these controls are:
BulletedList 20
CheckBoxList 6
DropDownList
ListBox
RadioButtonList
The controls capable of declarative data binding (a more complex data binding) are derived
from the abstract class CompositeDataBoundControl. These controls are:
DetailsView
FormView
GridView
RecordList
Simple Data Binding
Simple data binding involves the read-only selection lists. These controls can bind to
an array list or fields from a database. Selection lists takes two values from the
database or the data source; one value is displayed by the list and the other is
considered as the value corresponding to the display.
Let us take up a small example to understand the concept. Create a web site with a bulleted
list and a SqlDataSource control on it. Configure the data source control to retrieve two
values from your database Choosing a data source for the bulleted list control involves:
When the application is executed, check that the entire title column is bound to the bulleted
list and displayed.
20
7
Declarative Data Binding
The other composite data bound controls capable of displaying and manipulating
data in a tabular manner are the DetailsView, FormView, and RecordList control.
.However, the data binding involves the following objects:
A dataset that stores the data retrieved from the database.
The data provider, which retrieves data from the database by using a command over a
connection.
The data adapter that issues the select statement stored in the command object; it is
also capable of update the data in a database by issuing Insert, Delete, and Update
statements.
Relation between the data binding objects:
Example
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace databinding
{
public class booklist
{
protected String bookname;
protected String authorname;
public booklist(String bname, String aname)
{
this.bookname = bname;
this.authorname = aname;
<tr>
<td style="width: 228px; height: 40px;">
<asp:Label ID="lbllistbox" runat="server"></asp:Label>
</td>
21
<td style="height: 40px"> 0
<asp:Label ID="lbldrpdown" runat="server">
</asp:Label>
</td>
</tr>
<tr>
<td style="width: 228px; height: 21px">
</td>
<tr>
<td style="width: 228px; height: 21px">
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
</td>
<tr>
<td style="width: 228px; height: 21px">
<asp:Label ID="lblrdlist" runat="server">
</asp:Label>
</td>
</div>
</form>
Step (3) : Finally, write the following code behind routines of the application:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) 21
{ 1
IList bklist = createbooklist();
if (!this.IsPostBack)
{
this.ListBox1.DataSource = bklist;
this.ListBox1.DataTextField = "Book";
this.ListBox1.DataValueField = "Author";
this.DropDownList1.DataSource = bklist;
this.DropDownList1.DataTextField = "Book";
this.DropDownList1.DataValueField = "Author";
this.RadioButtonList1.DataSource = bklist;
this.RadioButtonList1.DataTextField = "Book";
this.RadioButtonList1.DataValueField = "Author";
this.CheckBoxList1.DataSource = bklist;
this.CheckBoxList1.DataTextField = "Book";
this.CheckBoxList1.DataValueField = "Author";
this.DataBind();
}
}
return allbooks;
} 21
2
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.lbllistbox.Text = this.ListBox1.SelectedValue;
}
21
3
Conclusion: ADO.NET is a data access technology from the Microsoft .NET Framework that
provides communication between relational and non-relational systems through a common
set of components.Crystal Report is a Reporting application that can generate reports
from various Data Sources .
21
4
Chapter 7:Crystal Reports
Crystal Report is a Reporting application that can generate reports from various Data Sources .
We can Create Reports , Print and Print Preview of reports from Crystal Reports . Crystal Reports
are compatible with most popular development environments like VB.NET etc.
7.1 CREATION:
Open Visual Studio .NET and select a new Visual Basic .NET Project.
Create a new Crystal Report for Product table from the above database crystalDB.
The Product Table has three fields (Product_id, Product_name, and Product_price).
From the main menu in Visual Studio select PROJECT-->Add New Item. Then Add
New Item dialogue will appear and select Crystal Reports from the dialogue box.
21
5
Accept the default settings and click OK.
Next step is to select the appropriate connection to your database. Here we are going
to select OLEDB connection for SQL Server
Then you will get your Server name under OLEDB Connection from there select
database name (Crystaldb) and click the tables , then you can see all your tables from
your database.
21
7
Click Next Button
Select all fields from Product table to the right side list.
21
8
Click Finish Button. Then you can see the Crystal Reports designer window. You can
arrange the design according your requirements. Your screen looks like the following
picture.
Call the created Crystal Reports in VB.NET through Crystal Reports Viewer
control.
Select the default form (Form1.vb) you created in VB.NET and drag a button
and CrystalReportViewer control to your form.
21
Select Form's source code view and put the code on top 9
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.CrystalReports.Engine
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim cryRpt As New ReportDocument
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
End Class
The Crystal Reports is in your project location, there you can see CrystalReport1.rpt. So give
the full path name of report here.
After you run the source code you will get the report like this.
Crystal Report Viewer control is a .NET control. You can add it to your windows
form or to web form so that you can display the report to the user. You can add this
control to the form by dragging it from the toolbox.
Crystal Report viewer control displays the report to the user at runtime. It has the
option to print, search, browse through the pages of the report. It has also had the
option to export the report. This Option found at the top left corner of the Report
22
1
Export Crystal Report Using Windows Application
ExportToDisk
Use this option to export the report to disk. Method has following Option
The format type to export the report. FormatType could be PDF, Excel etc. This
parameter is explained in detail below fileName
22
The file name to export the report with full path 2
B) Conclusion
We can Create Reports , Print and Print Preview of reports from Crystal Reports .
Crystal Reports are compatible with most popular development environments like
VB.NET etc.
MCQ’S
1. To use the .NET Framework Data Provider for SQL Server, an application must
reference the _____________ namespace.
a) System.Data.Client
b) System.Data.SqlClient
c) System.Data.Sql
d) None of the mentioned
4. Code snippet for having a named instance of SQL Server would be ___________
a) ―Server=localhost\sqlexpress‖ 22
b) ―Server=local\sqlexpress‖ 3
c) ―Server=host\sqlexpress‖
d) ―Ser=localhost\sqlexpress‖
a) End user need to have the crystal report viewer in his PC in order to see the crystal report
output. But this can be overcome if you export the report as PDF/HTML
b) You need to buy Crystal Report license for each pc you are used to design the crystal
report 22
c) Must buy the version which allows you to install run time components in end user PC 4
d )All of these
13. What do you need to add to a project in order to create and display a simple report using
Crystal Reports?
A. CrystalReportSource control
B. CrystalReportViewer control
C. CrystalReportSource and CrystalReportViewer controls
D. CrystalReportViewer control and a reference to CrystalReports
15. To fill a dataset for a report include ____________________ at the top of the file.
A. Imports CrystalDecisions.CrystalReports
B. CrystalDecisions.CrystalReports.Engine
C. Exports CrystalDecisions.CrystalReports.Engine
D. Imports CrystalDecisions.CrystalReports.Engine
Q1. What are the main differences between classic ADO and ADO.NET?
ADO have recordset. ADO.NET have data adopter and data set.
The objects of ado communicate in binary mode. It uses XML for passing the data.
It derives information about data implicitly at It uses known metadata at design time, so it
runtime based on metadata, so it is a costly provides better runtime performance and
process. more consistent runtime behavior.
It allows only client-side cursors. It supports both client side and server side
cursors
22
Q2. What is the difference between Data Reader and Data Adapter? 5
Data Reader Data Adopter
Data reader facilitates you to open and close connection If you use data adopter, the
explicitly. connection is automatically open and
closed.
Crystal report is a window based report writer that enables the programmer to make reports
from different data sources with a minimum of written code. Crystal report can access data
from various data-bases and can synchronize data from multiple databases into a single
report.
Q6. Explain how can you connect crystal report to the databases?
Assignment 1:
Q1. Explain ADO.NET architecture and it‘s components in detail.
Q2. Write short note on Data set, Data Reader and Connection objects.
Q3.what is crystal report?
Q4. WAP with the ADO.NET code to insert the record into employee table containing the
colums such as emp_id,emp_name and salary.
22
Assignment 2:
7
Q1. Write steps to create crystal report.
Q2. What is ADO.NET? disscuss ADO.NET model with it‘s characterists.
Q3. Explain different sections of a crystal report.
Q4. Write short note on data binding and data adapter.
22
8