You are on page 1of 228

Maharaja Surajmal Institute

(Affiliated to GGSIPU, Delhi)

Course : Bachelor of Computer Application


Subject Module
On
Front End Design Tools E-Module (BCA-205)
Semester III (Credit: 4)

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

1.2 Application Development 8

1.3 The .NET Framework 12

1.4 .NET Architecture 14

1.5 Common Type System 17

1.6 Assemblies in Common Language Runtime 20

1.7 Memory Management Issues 22

1.8 Exception Handling 26

1.8.1 Structured Exception Handling 26

1.8.2 User Defined Exception 29

1.8.3 Unstructured Exception 30

1.9 Code Access Security 33

Unit II
Chapter 2: Introduction to Visual Basic.Net IDE

2.1 Introduction 41

2.2 Creating a project 43

2.3 Types of project in .Net 46

2.4 Exploring and coding a project 46

2.5 Solution explorer 47

2.6 Toolbox 47

2.7 Properties window 48

2.8 Output window 48 3

2.9 Object Browser 49


Chapter 3: VB.Net Programming Language

3.1 Introduction to VB.Net 51

3.2 Similarities and Differences with Visual Basic 51

3.3 Variables 52

3.4 Constants 53

3.5 Comments 55

3.6 Data Types 57

3.7 Working with Data Structures :Arrays 59

3.8 Array Lists 62

3.9 Enumerations 62

3.10 Structures 65

3.11 Introduction to procedures: 68

3.11.1 Sub Procedures 68

3.11.2 Functions Procedures 71

3.12 Conditional statement 74

3.12.1 If..End if statements 75

3.12.2 If..Else..End if statements and 76

3.12.3 Select..case..End Select statements. 78

3.13 Loops 80

3.13.1 While..End While 80


3.13.2 Do..Loop 81
3.13.3 For..Next 81
3.13.4 For Each..Next 82
3.14 Nesting of Loops 82

3.15 MsgBox and Input Box 84

4
UNIT III
Chapter 4: GUI Programming

4.1 GUI Programming 91

4.2 Windows Forms 92

4.3 Introduction to Common Controls 93

4.3.1 Properties 94

4.3.2 Methods 94

4.3.3 Events 94

4.4 CREATING CONTROLS IN VB.NET 95

4.5 Textbox 97

4.6 Label 100

4.7 Button 101

4.8 Listbox 104

4.9 Combobox 107

4.10 Picture Box 111

4.11 Checkbox 114

4.12 Radio Button 117

4.13 Panel 120

4.14 Scroll bar 122

4.15 Timer 125

4.16 ListView 126

4.17 TreeView 130

4.18 Toolbar 134

4.19 Status Bar 140

4.20 Dialog Controls 142

4.21 Creating and Using MDI applications 143


5
4.22 Creating Menus 148
Chapter 5: Object Oriented Features

5.1 Object Oriented Programming 158

5.2 Classes and Objects 159

5.3 Properties and Methods 160

5.4 Constructors and Destructors 164

5.5 Overloading 167

5.6 Overriding 171

5.7 Access Specifiers: Private, Public and Protected 176

5.8 Inheritance 178

5.9 Abstract and Final classes 180

5.10 Interfaces 182

5.11 Creating and Using Namespaces 184

UNIT IV
Chapter 6: Introduction to ADO

6.1 ADO vs ADO.Net 189

6.2 ADO.Net data namespaces 190

6.3 ADO.Net Object Model 191

6.4 Connection Object 192

6.5 Command Object 193

6.6 Command Builder 194

6.7 DataAdapter Object 194

6.8 DataSet Structure 195

6.9 DATABASE CONNECTIVITY 196

6.10 Data Binding 206

Chapter 7: Crystal Report

7.1 CREATION 215


6
7.2 Exporting a crystal report 220
Lesson 1: Introduction to .NET

Learning Outcomes of the unit:

After completing this unit/lesson, the students will be able to:

 Understand .NET Technology


 Learn Two Tier and Three Tier Client Server Model
 Learn Feature and Advantages of .NET
 Learn .NET Framework
 Learn CLS, CTS, CLS
 Understand the .NET memory management
 Learn Exception Handling in .NET
 Learn Code Access Security

1.1 Introduction to .Net

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 consistent object-oriented programming environment whether object code is


stored or on distributed network and executed locally or remotely.

•To provide a code-execution environment that minimizes software deployment and


versioning conflicts.

•To provide a code-execution environment that promotes safe execution of code by providing
code access security.

•To provide a code-execution environment that eliminates the performance problems of


scripted or interpreted environments. 7
•To make the developer experience consistent across varying types of applications, such as
Windows-based applications and Web-based applications.

•To build all communication on industry standards to ensure that code based on the .NET
Framework can integrate with any code.

1.2 Application Development

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.

The three types of application architecture are: 8


 Single-tier (or monolithic),
 Two-tier
 N-tier, where n can be three or more.
The monolithic application consists of a single application layer that supports the user
services, business services and data services all in one layer. The data itself could be
physically stored in a remote location, but the logic for accessing data is part of the
application. Numerous Windows/Linux applications are example of a monolithic application.
Taking example of Microsoft Word, the user interface is an integral part of the application.
The business rules, such as how to indent and format, are also part of the application. The file
access routines, to manipulate the data of the document, are also part of the application. The
application need to call multiple DLLs to handle different functionality, it is still a monolithic
application.

Monolithic Application

User Services Business Services Data Services

Figure 1.1 Single Tier architecture


In a two-tier application, the business services and user services remains the part of the client
application. The data retrieval and manipulation is performed by another separate application,
usually found on a physically different system. This separate application could be SQL
Server, Oracle or any other database system, which functions as data storage for the
application. This type of application is widely used in the traditional client-server types of
applications.
Library Management System, Grocery Shop Bill Management system, Student Information
System running in a local network environment is example of 2 Tier applications. These
applications store their data on Database Server.
In another type of two-tier application, the business rules are executed on the data storage
system. These types of applications make use of stored procedures to manipulate the
database. A stored procedure is a database function that is stored at the database server. A
client application can explicitly call these stored procedures, which would run on the server.
A trigger can also execute a stored procedure, which is the occurrence of a specific event in
the data. For example, a trigger is fired whenever the return date of book expires in Library
Management System which in turn execute stored procedure that sends a notification to the
library members.

Fat Server
Fat Client

User Services Business Services Data Services 9


Figure 1.2 : 2 Tier architecture: Business service is present either at Client or Database Server

Advantages:

1. It is easy to maintain and modify.


2. The Communication is faster in two tier architecture.
3. Business logic can be shifted to client side or server side depending on the client and
server configuration.
4. Business logic can be categorized by understanding the task involved. Data validation
can be placed on the client side, it eases the burden of server for first level check.
Business logic and processing of data can be placed on the server side.
Disadvantages:

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.

Client Business Logic Data Store

User Services Business Services Data Services

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:

1. High performance, lightweight persistent objects.


2. Scalability – Each tier can scale horizontally. 11
3. Performance – The Presentation tier can cache requests thereby network utilization is
minimized, and the load is reduced on the Application and Data tiers.
4. It has high degree of flexibility in deployment platform and configuration.
5. It provides re-usability.
6. It provides data integrity.
7. It provides improved security as client is not able to directly access the database.
8. It is easy to maintain as modification in one tier doesn‘t affect other tiers.
9. The overall application performance is good.
Disadvantages:

1. It increases the application complexity and efforts.


2. It is cost in-effective as you need to maintain three tiers separately.

1.3 The .NET Framework

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:

Memory management- In many programming languages, programmers are responsible for


allocating and releasing memory and for handling object lifetimes. In .NET Framework
applications, the CLR provides these services on behalf of the application.

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.

To develop .NET Framework applications or components, do the following:

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.

1.4 .NET Architecture

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.

VB.NET C# JScript.NET More .NET Languages

Common Language Specification (CLS)

Common Type System (CTS)

.NET Framework Class Library (FCL)

ASP .NET Windows Forms Console

Web Forms, XML, Web Services


ADO .NET .NET Remoting

Common Language Runtime

[Just-in-Time, Garbage Collector, Security Manager and so on]


Operating System

Figure 1.4 .NET Framework Architecture

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.

Just In Time Compiler


Code in any .NET Language Compiler MSIL Code Executable Native
language Code
compile time runtime

Figure 1.5 Compilation process in .NET

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.

The common type system performs the following functions:

•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.

Common Language Specification (CLS): The CLS ensures language interoperability by


defining a set of features that all languages must follow that run under .NET Framework. The
CLS was designed to be large enough to include the language constructs that are commonly
needed by developers, yet small enough that most languages can support it. The complete
reference to CLS features can be referred from the .NET Framework documentation.

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:

Keywords: CLS compliant language compilers supply a mechanism for referencing


identifiers that coincide with keywords. CLS provides a mechanism for defining and
overriding virtual methods that have same name as keywords.

Uniqueness: CLS-complaint language allows identifier name to be unique within a specific


scope. However, CLS allows overloading where two functions can have same name.

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.

1.5 Common Type System

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:

 All numeric data types


 Boolean, Char, and Date
 All structures, even if their members are reference types
 Enumerations, since their underlying type is always SByte, Short, Integer, Long,
Byte, UShort, UInteger, or ULong

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

Dim x As Decimal = New Decimal (1, 5, 10, False, 2)


In the above example variable x is declared using New keyword as it calls the Decimal
(Int32, Int32, Int32, Boolean, Byte) constructor, which builds a new Decimal value from the
supplied parts.

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.

Public Class Box

Private length As Integer

Private breadth As Integer

Private height As Integer

Public Function getVolume() As Integer

getVolume = length * breadth * height

End Function

End Class

Dim myBox1 As New Box()

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.

1.6 Assemblies in Common Language Runtime

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

We can create three types of Assembly:

1. Private Assembly: A private Assembly is used only by a single application, and


usually it is stored in that application's install directory.
2. Shared Assembly: A shared Assembly is one that can be referenced by more than one
application. If multiple applications need to access an Assembly, we should add the
Assembly to the Global Assembly Cache (GAC). 20
3. Satellite Assembly: A Satellite Assembly contains only static objects like images and
other non-executable files required by the application.
An assembly performs the following functions:

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.

In general, a static assembly can consist of four elements:

 The assembly manifest, which contains assembly metadata.


 Type metadata.
 Microsoft intermediate language (MSIL) code that implements the types.
 A set of resources.
There are several ways to group these elements in an assembly. You can group all elements
in a single physical file, which is shown in the following figure.
21
Single file assembly

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.

In the following illustration, the developer of a hypothetical application has chosen to


separate some utility code into a different module and to keep a large resource file (in this
case a .bmp image) in its original file. The .NET Framework downloads a file only when it is
referenced; keeping infrequently referenced code in a separate file from the application
optimizes code download.

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.

1.7 Memory Management Issues

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.

Generation 2 Objects Any generation can have


some unreachable objects
Allocated Space Generation 1 Objects
in it
Generation 0 Objects
Allocation Pointer
Committed (ready to use)

Uncommitted (Reserved)
Free Space

Figure 1.6 : Model of the managed heap

The simple model followed by garbage collector follows certain rules:

 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

Root Live Object (a) Live Object (a)

Dead Object (b) Live Object (c)

Live Object (c) Live Object (e)

Dead Object (d) Free Space


Root Live Object (e)
Root Dead Object (f)

Free Space

Figure 1.7 Garbage Collection

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.

1.8 Exception Handling

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.

Visual Basic.NET supports two types of Structured Exception Handling:

Structured Error Handling: Structured exception handling uses a control structure


containing exceptions, isolated blocks of code, and filters to create an exception handling
mechanism. This allows your code to differentiate between different types of errors and react
in accordance with circumstances.

Unstructured Error Handling: In unstructured exception handling, an On Error statement


at the beginning of the code handles all exceptions.

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.

1.8.1 Structured Exception Handling


26
Structured exception handling is built upon four keywords: try, catch, throw and finally. In
the most general terms, program statements that you want to monitor for exceptions are
contained in try..end try block. Exceptions that can be thrown by the monitored code are
caught by a catch statement, which immediately follows the try statement in which the
exception was thrown. There can be one or more catch blocks, each designed to handle a
particular type of exception, or one block designed to catch a more specific exception than
another block.A program can throw its own exception when some problem arise using throw
keyword. The Finally statement contains code that executes regardless of whether or not an
exception occurs within the Try block

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.

The general form of try and catch are:

Try

//try block statement

throw

Catch ex As Exception

//catch statement

Finally

//finally block

End Try

Program 1.2: TO demonstrate the structured error handling


1 Module Module1
2 Sub Main()
3 Dim num1, num2, num3 As Integer
4 Try
5 System.Console.WriteLine("Enter Dividend‖)
6 num1 = System.Console.ReadLine
7 System.Console.WriteLine("Enter Divisor‖)
8 num2 = System.Console.ReadLine
9 num3 = num1 / num3 27
10 System.Console.WriteLine("Division Answer:=" + num3)
11 If num3 < 10 Then Throw New Exception
12 Catch e As ArithmeticException
13 System.Console.WriteLine("Error raised:" + e.ToString)
14 Catch e As Exception
15 System.Console.WriteLine("Error raised:" + e.ToString)
16 Finally
17 System.Console.ReadKey()
18 End Try
19 End Sub
20 End Module
Output:
Enter Dividend 10
Enter Divisor 0
Error raised: System.OverflowException: Arithmetic operation resulted in an overflow.

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.

1.8.2 User Defined Exception

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.

1.8.3 Unstructured Exception


Unstructured exception handling is implemented by making use of the Err object and three
statements: On Error, Resume, and Error. The On Error statement creates a single 30
exception handler that catches all thrown exceptions; you can subsequently change the
handler location, but you can only have one handler at a time. The method keeps track of the
most recently thrown exception and the most recent exception-handler location. At entry to
the method, both the exception and the exception-handler location are set to Nothing.
To generate a run-time error in your code,Raise method should be used. Whenever an Exit
Sub, Exit Function, Exit Property, Resume or Resume Next statement occurs within an
error-handling routine, the Err object's properties are reset to zero or zero-length strings.
Using any of these outside an error-handling routine does not reset its properties. If you want
to do so, you can use the Clear method to reset the Err object.

The Error Object

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.

Table 1.1 : Properties and description of Err object


Property Description
Description Text message providing a short description of the error.
HelpContext Integer containing the context ID for a topic in a Help file.
HelpFile String expression containing the fully qualified path to a
Help file.
LastDLLError System error code produced by a call to a dynamic-link
library (DLL). This is the most recently called DLL before
the error happened.
Number Numeric value specifying an error.
Source String expression representing the object or application that
generated the error.

The following example shows unstructured error handling:

Program 1.4: TO demonstrate unstructured exception handling


1 Module Module1
2 Sub Main()
3 Dim num1, num2, num3 As Integer
4 On Error Resume Next
5 System.Console.WriteLine("Enter Dividend")
6 num1 = System.Console.ReadLine
7 System.Console.WriteLine("Enter Divisor")
8 num2 = System.Console.ReadLine
9 num3 = num1 / num2
10 System.Console.WriteLine("Division Answer:=" & num3)
11 System.Console.ReadKey()
12 End Sub
13 End Module
31
Output:
Enter Dividend 10
Enter Divisor 0
Division Answer:=0
Enter Dividend 10
Enter Divisor 5
Division Answer:=2

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.

Program 1.5: TO demonstrate unstructured exception handling using On Error GoTo


label
1 Module Module1
2 Sub Main()
3 Dim num1, num2, num3 As Integer
4 On Error GoTo lbl
5 System.Console.WriteLine("Enter Dividend")
6 num1 = System.Console.ReadLine
7 System.Console.WriteLine("Enter Divisor")
8 num2 = System.Console.ReadLine
9 num3 = num1 / num2
10 System.Console.WriteLine("Division Answer:=" & num3)
11 lbl:
12 System.Console.WriteLine("Error No: " & Err.Number & Err.Description)
13 System.Console.ReadKey()
End Sub
End Module
Output:
Enter Dividend 10
Enter Divisor 0
Error No: 6 Arithmetic operation resulted in an overflow

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

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.

Table 1.2: Usage of OnError, GoTo statement


Statement Purpose
On Error GoTo -1 Resets Err object to Nothing, disabling error handling in the
routine
On Error GoTo 0 Resets last exception-handler location to Nothing, disabling
the exception.
On Error GoTo Sets the specified label as the location of the exception
<labelname> handler
On Error Resume Establishes the Resume Next behavior as the location of the
Next most recent exception handler

Resume and Resume Next

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

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.

1.9 Code Access Security

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.

Components of Code Access Security

Given below are the three components of Code Access Security.

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

Multiple Choice Questions

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)

2. The .NET Framework Class Library (FCL) is also known as …


A) Base Class Library (BCL)
B) Common Class Library (CCL)
C) Global Class Library (GCL)
D) Public Class Library (PCL)

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

13. The … is responsible for allocating, freeing, and compacting memory.


A) garbage collector
B) type checker
C) code manager 37
D) memory manager
14. The … compiles the applications to Microsoft Intermediate Language (MSIL) and not the
machine code.
A) CLR
B) CTS
C) CLS
D) FCL

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. B) Common Language Runtime (CLR)


2. A) Base Class Library (BCL)
3. C) i-True, ii-True
4. D) Framework Class Library (FCL)
5. A) Common Language Specifications (CLS)
6. C) Common Type System (CTS)
7. B) ii and iii only
8. D) MSIL
9. C) i-True, ii-True
10. A) CLR
11. D) All i, ii and iii
12. B) Type checker
13. A) garbage collector
14. A) CLR
15. C) i-True, ii-False, iii-True
16. B) CLS
17. C) i and iii only
18. A) system.collection
19. C) system.diagnostics
20. D) system.reflection
Long Answer Questions

Q1. Explain the 3-tier computing model.


Q2. Explain 2-tier client server architecture.
Q3. What are the major components of .NET framework?
Q4. Explain the Framework Class Library.
Q5. What is Code Access Security?
Q6. Differentiate between CLR, CTS and CLS.
Q7. What is Memory Management in .NET? Describe its types.
Q8. What are the various components in IDE? 39
Q9. Explain Garbage Collector and its uses.
Q10. What are Assemblies? How many types of Assembly exist?
Q11. What is Exception handling? Explain Exception Handling techniques with suitable
examples.
Q12. Explain the property and method of Error Object.

Suggested Skill Development Projects/Assignments:


Students can create a working project on Library Management, Students Management or
Billing System using the skills learned in this curriculum.

Essential and Additional Readings:

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:

 After completing this unit/lesson, the students will be able to:


 Understand VB IDE.
 Know about the projects, properties windows and toolbox controls.
 Learn procedure how to install Dot Net

2.1 Introduction

Visual Studio is an Integrated Development Environment (IDE) developed by Microsoft


to develop GUI(Graphical User Interface), console, Web applications, web apps, mobile
apps, cloud, and web services, etc. It can also be used to develop ASP Web applications,
XML Web services, desktop applications, and mobile applications. With the help of this
IDE, you can create managed code as well as native code. it is not a language-specific IDE
as you can use this to write code in C#, C++, VB(Visual Basic), Python, JavaScript, and
many more languages. It provides support for 36 different programming languages. It is
available for Windows as well as for macOS.

Features and IDE :

.NET Introduced with Description


Framework IDE
version
1.0 Visual Studio .NET Contained the first version of the CLR and the first version of the
base class libraries.
1.1 Visual Studio .NET Included updates to ASP.NET and ADO.NET. It was
2003 subsequently updated twice, with Service Pack 1 (SP1) and SP2.
It added side-by-side execution, enabling apps on a single
computer to run against multiple versions of the CLR.
2.0 Visual Studio 2005 Introduced a new version of the CLR with additions to the base
class libraries, including generics, generic collections, and
significant additions to ASP.NET. This version was updated with
SP1 and SP2.
3.0 Visual Studio 2005 This version is essentially .NET Framework 2.0 with the addition
of Windows Presentation Foundation (WPF), Windows
Communications Foundation (WCF), Windows Workflow
Foundation (WF), and CardSpace. It was updated with SP1 and
SP2.
3.5 Visual Studio 2008 Added new features such as AJAX-enabled websites and LINQ.
The SP1 update added Dynamic Data, and a small set of
additional enhancements.
4 Visual Studio 2010 Included a new version of the CLR, expanded base class libraries,
and new features such as the Managed Extensibility Framework
(MEF), dynamic language runtime (DLR), and code contracts.
4.5 Visual Studio 2012 Includes an updated version of the CLR, support for building41
Windows Store apps, and updates to WPF, WCF, WF, and
ASP.NET.
Features of Visual Studio .NET

Various features of Visual Studio are summarized as

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.

2.2 Creating a new project in Dot Net Application :

A Visual Basic Project is container for the forms, methods, classes, controls that are used for
and Visual Basic Application.

Steps to Create a VB.net Project:

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.

2.4 Exploring and coding a project :

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.

2.8 Output Window

 The Output window displays status messages for various features in the integrated
development environment (IDE).

 It shows the different stages outputs

 To open the Output window, on the menu bar, choose View > Output, or press
Ctrl+Alt+O.

Components of output box

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.

Clear all: Clears all text from the Output pane.

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.

2.9 Object Browser

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

3.1 Introduction to VB.Net:

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)

• .Net is a new framework for developing web-based and windows-based applications


within the Microsoft environment.

• The framework offers a fundamental shift in Microsoft strategy: it moves application


development from client-centric to server-centric.

3.2 Similarities and Differences with Visual Basic

Similarities between visual basic and visual basic.net

 Both visual basic and visual basic.net are provided by Microsoft.


 Basic syntax of VB and VB.NET is similar : Conditions , loops etc are declared
and written in similar manner.
 VB.NET is basically a successor of VB.The main feature that has been added in
VB.NET is the concept of managed code.
 A programmer who has only worked with visual basic may find it difficult to cope 51
with VB.NET.
Difference between visual basicand visual basic.net

3.3 Variables in VB.NET

We can declare a variable StudentID to be of type Integer as follows:


Dim StudentID as Integer
Examples of valid variable names: interest_rate, address2, phone#

Names like 2mark, tom.sawyer, &another are invalid.

Using variables

Variables can be initialized or assigned a value anywhere within the program after they have
been declared.

Dim max_marks as Integer


Max_marks =100
VB.NET assigns a default value to a variable depending upon its data type

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

Syntax to declare a constant is as follows:


53
[Public | Private | Friend | Protected |Protected Friend] Const constantname [As type] =
expression
Example:

Public Const DaysInYear = 365

Private Const WorkDays = 250

Example demonstrating declaration and use of a constant value:

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

Data Type Capacity Description/Range

Byte 8 -bit
Range: 0 to 255.

Short
16 bit Range: –32768 to +32767

Integer Can store values in the range from – 2,147,483,648 to


32-bit
+2,147,483,647.

Long Can store values ranging from –9,223,372,036,854,775,808 to +


64- bit
9,223,372,036,854,775,807.
Divided into two parts- a 96-bit integer for storing the integer
Decimal
128- bit part of the decimal number and an associated 32-bit integer for
storing the decimal part.
Can store values ranging from -3.402823E38 to -1.401298E-45
Single
32-bit for negative numbers and from 1.401298E-45 to 3.402823E38
for positive numbers.

It can range from 1.79769313486232E308 to -


Double
64-bit 4.940654581247E-324 for -ve numbers and +4.940654581247E-
324 to +1.79769313486232E308 for +ve

Boolean 16 bit
Represents numbers as True or False

Char 16-bit Unicode values in the range 0 to 65535

31
String - Can store 2^ Unicode characters.

Object - Can hold any type of data

Option Statement

Option Statement Value Description


Option Explicit On Requires declaration of all variables before
they are used (default)
Off Variables can be used without declaring them.
Option Compare Binary Strings are compared using binary comparison
algorithm (default)
Text Strings are compared using text algorithm
Option Strict On Automatic type conversion will not take place
Off Automatic type conversion will take place 57
(default)
Typecasting

Typecasting is the process of converting from one data type to another.


Dim n1 As Integer
Dim quotient As Decimal
n1 = 5
quotient = n1 / 2
Console.WriteLine(quotient)

Option Strict

If Option Strict is On, type casting will not be done automatically.

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

Output is:-- 5.5


3.7 Working with Data Structures : Arrays

 Arrays are objects in VB.net


 An of any fundamental data type, of a structure or of an object class.
 Array variables can have the Public, Protected, Friend, Private or Protected Friend
specifier.

Dim Expenditure(366) As Decimal


Dim I As Integer
For I = 0 to 365
Expenditure(I) = 20
Next I
The above code declares the array variable CurExpense, initializes it to have 366 elements,
and then assigns an initial value of 20 to each element.

Dim EmpData(3) As Object

EmpData(0) = "astalavista"

EmpData(1) = "42 Heaven Towers"

EmpData(2) = 100

EmpData(3) = Format("09-10-1992", "Date")

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.

Dim Num1, Num2 As Integer

Dim MDim0, MDim1 As Integer

Dim MatA(10, 10) As Double

MDim0 = MatA.GetLength(0) – 1

MDim1 = MatA.GetLength(1) - 1

For Num1 = 0 To MDim0

For Num2 = 0 To MDim1

MatA(Num1, Num2) = (Num1 * 10) + Num2

Next Num2
59
Next Num1
Redim statement

ReDim Preserve MyArray(10, 20)

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.

Creating Multidimensional Arrays

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

• In case of multidimensional array, ReDim can be optionally followed by the Preserve


keyword if only the last dimension of the array is changed.

Dim X(3,3) as Integer

...

...

Redim Preserve X(3,5)

Arrays and Exceptions

When using arrays care must be taken to avoid exceptions.

Using an index position that exceeds the limit of the array will cause an

IndexOutOfRangeException.

Module m

Sub Main()

Dim values() As Boolean={False,True,True}

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.

Syntax : Enum <name> [ as <fundamental type>]

Value1

Value2

...

End Enum

Using Enumerations

Enum Cities as Short

Illinois

Denver

Plano

Austin 62

End Enum
Here ,

Illinois0
Denver1
The member Plano could be used as
UserCity = Cities.Plano
Assuming, UserCity is declared as a variable of Short type.
Demonstrating Enumerations

Module m

Enum Cities as Short

Illinois

Denver

Plano

Austin

End Enum

Sub Main()

System.Console.WriteLine(Cities.Plano)

End Sub

End Module

Members Sharing Same Value

Enum Cities as Short

Illinois

Denver

Plano

Austin=Denver

End Enum

Two enumeration members Austin and


63
Denver share the same value of 3.
Using Enumerations

Enum Grade as Byte

A=100

B=80

C=70

D=60

E=40

End Enum

Module m

Sub Main()

Dim gradevalue as byte

System.Console.WriteLine("Enter marks")

gradevalue=System.Console.ReadLine()

Select case gradevalue

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

Public Structure Book

Public Title as String

Public Author as String

Public Pages as Integer

Public Price as Single

End structure

Sub Main()

Dim b as new Book()

b.Title=System.Console.ReadLine()

b.Author=System.Console.ReadLine()

b.Pages=System.Console.ReadLine()

b.Price=System.Console.ReadLine()

End Sub

End Module

Using Arrays with Structures

Module m 65

Public Structure X
Public Y as Integer

Public Arr( ) as Integer

End Structure

Sub Main()

Dim Obj as X

Redim Obj.Arr (1)

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

Using Procedures with Structures

Module m

Structure stud

Public Name as String

Public rollno as Integer

Public Sub accept()

System.Console.WriteLine("Enter student name and rollno")

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

Using a Structure within a Structure

Module m

Structure dateofbirth

Public day as Integer

Public month as Integer

Public year as Integer

End structure

Structure stud

Public name as String

Public rollno as Integer

Public dob as dateofbirth

Public sub accept()

name=System.Console.ReadLine()

rollno=System.Console.ReadLine()

End Sub

Public Sub acceptdob()

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("The student details are ")

System.Console.WriteLine(s.name)

System.console.writeLine(s.rollno)

System.Console.Write(s.dob.day & ―/‖)

System.Console.Write(s.dob.month & ―/‖)

System.Console.WriteLine(s.dob.year)

End sub

End module

3.11 Introduction to procedures: Sub Procedures and Functions Procedures

Procedures and functions are

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

Procedures and functions are blocks of code in a program.

3.11.1 Sub Procedure

A Sub procedure is called using the procedure name, followed by the argument list in
parentheses.

Alternatively, the Call statement can be used to call a Sub procedure.

A Sub procedure can accept arguments; however, it cannot return a value to the
calling procedure.

A procedure is declared as Sub in VB.Net and cannot be declared inside another


procedure. 68
Defining Procedures

A VB.NET procedure is written within a Sub..End Sub block

[ <attrlist> ] [{ Overloads | Overrides | Overridable | NotOverridable | MustOverride |


Shadows | Shared }]

[Protected| Friend| Protected Friend| Private]

Sub subname[(argumentlist)]

Statements

End Sub

Example:--

Module M

Sub main( )

Dim j as Integer

j=System.Console.Readline()

Square(j) ‗Procedure call

System.Console.WriteLine("End of main program")

End Sub

Sub Square(x as Integer)

System.Console.WriteLine(x*x)

End Sub

End Module

Exit Sub and Return statements

To terminate a procedure, we can make use of the Exit Sub statement.

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.

Exit Sub statement causes an immediate exit from a Sub procedure

A Return statement can also be used to immediately exit the procedure

It is also possible to combine Exit Sub and Return statements 69


Example:--

1)Module M

Sub Main( )

Dim attendance as Char

System.Console.WriteLine (―Enter attendance‖)

System.Console.WriteLine ( ―R for Regular, A for absentee and I for irregular‖)

attendance=System.Console.ReadLine( )

total(attendance)

End Sub
Sub total(x as Char)
Dim marks1 as Integer

Dim marks2 as Integer

Dim marks3 as Integer

Dim ave as Single

If x="A" or X="I"

System.Console.WriteLine("Absentee or irregular hence no results


calculated")

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

System.Console.WriteLine("Average marks is " & ave)

End Sub

End Module 70
2) Sub SubComputeArea(ByVal Len As Double, ByVal Wid As Double)

Dim Peri As Double ' Declare local variable.

If Len = 0 Or Wid = 0 Then ' If either argument = 0.


Exit Sub ' Exit Sub immediately.
End If
Peri = 2*(Len + Wid ) ' Calculate area of rectangle.
System.Console.WriteLine(Peri) ' Print Area to Immediate window.
End Sub

3.11.2 Function procedures

A Function procedure can be defined inside a module, class, interface, or structure,


but not inside another procedure.

Function procedures are Public by default.

Function Procedures return values whereas Sub Procedures cannot return a value to
the calling procedure.

[ <attrlist> ] [{ Overloads | Overrides | Overridable | NotOverridable | MustOverride |


Shadows | Shared }]

[{ Public | Protected | Friend | Protected Friend | Private }] Function name[(arglist)]


[ As type ]
[ statements ]
[ Exit Function ]
[ statements ]
End Function

Calling functions

• A call to a Function procedure is made by using the function procedure name,


followed by the argument list in parentheses.

• 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.

Passing arguments by value

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

Sub Increment(ByVal 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

Passing arguments by reference

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

• Optional arguments are indicated by the Optional keyword in the procedure


definition.

• Every optional argument in the procedure definition must specify a default value,
which must be a constant.

• Arguments following an optional argument in the procedure definition must also be


declared as optional.

Syntax :

Sub subname(ByVal arg1 As type1, Optional ByVal arg2 As type2 = defaultvalue)

We could supply the first and fourth arguments but omit the second or third arguments.

Call subname(arg1, , , arg4) ' Leaves out arg2 and arg3.

Sub Notify (ByVal Company As String, Optional ByVal Location As String = "None")

If Location = "None" Then

System.Console.WriteLine("Location not supplied –assume to be

Palo Alto,CA")

Location = "Palo Alto, CA"

End If

End Sub

Dim flag as Boolean

If flag=false

Dim x as Integer

x=100

System.Console.WriteLine(x)

End if

3.12 Control Flow Statements – Conditional statement

• Decision constructs are used to represent conditions and the actions to be taken based
on the outcomes of the conditions. 74

• VB.NET supports 3 styles of decision constructs:


 If..End if statements

 If..Else..End if statements and

 Select..case..End Select statements.

3.12.1 IF..End IF Statement

An If..End If statement consists of a condition with an expression that evaluates to a Boolean


True or False.

If <condition1> [Then]
Statement1
End if
Example: If answer=―yes‖ Then

System.Console.WriteLine(―Answer is yes‖)
End if

If then Else Statement

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.

If selling_price > cost_price


Profit=selling_price-cost_price
System.Console.WriteLine(―Profit is‖&profit)
Else
Loss=cost_price-selling_price
System.Console.WriteLine(―Loss is‖&loss)
End if

3.12.2 Usage of If..Else..Endif

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

Using Series in Select Expression


Dim n as Integer
System.Console.WriteLine (―Enter marks scored‖)
n=System.Console.Readline( )
Select case n
Case 0 to 35
System.Console.WriteLine("Fail")
Case 39 to 59
System.Console.WriteLine("Pass class")
Case 59 to 97
System.Console.WriteLine("Good Record")
Case 98,99,100
System.Console.WriteLine("Exceptional!!")
End select

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 Loop constructs


• A loop construct is used whenever a statement or a group of statements have to be
executed a number of times.
• VB.NET supports the following types of loops:
• While..End While
• Do..Loop
• For..Next
• For Each..Next

3.13.1 While..End While Loop


While <condition>
Statement(s)
End While 80
The statements within While…End While block execute as long as condition is true.
Example:
Module Module1
Sub Main( )
Dim x as Integer
x=1
While x<10
System.Console.WriteLine(x)
x=x+1
End while
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

3.13.3 For..Next Loop


A For...Next statement specifies a lower limit, a higher limit, and an optional step value.
Syntax of this loop construct is:
For index =<range_begin> to <range_end>
[step <value>]
Statement(s) 81
Next <index>
Example:
Module Module1
Sub Main( )
Dim x as integer
For x = 1 to 9
System.Console.WriteLine(x)
Next x
End sub
End Module
There is no additional increment statement within the loop. This is because in a For..Next
loop, incrementing is done automatically.

3.13.4 For..Each..Next loop


This loop is generally used to iterate through collections or arrays.
The syntax of For Each..Next loop is as follows:
For Each <index> in <Collection>
Statement(s)
Next <index>

3.14 Nested loops


Module Module1
Sub Main( )
Dim i as integer
Dim j as integer
For i=1 to 10
For j=1 to i
System.Console.WriteLine("*")
Next j
System.Console.WriteLine( )
Next i 82

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

Using Exit in Nested Loop


Module Module1
Sub Main()
Dim i as Integer
dim j as Integer

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

3.15 InputBox and MsgBox functions

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:

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


Handles Button1.Click

Dim strName As String

strName = InputBox("What is your name?")

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.

For example, this program:

Dim strUserIn As String

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:

Code Buttons displayed

0 OK (the default)

1 OK and Cancel

2 Abort, Retry, and Ignore

3 Yes, No, and Cancel

4 Yes and No

5 Retry and Cancel

For example, this program:

Dim intButton As Integer intButton = MsgBox("This is the message", 3, "This is the title")

produces this InputBox:

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:

The user clicked Value returned

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.

A) Progress Check: MCQ’s and long answer question


1. ………………… datatype in .Net FCL corresponds integer data type in vb.net.
A) System.Int32
B) System.Int64
C) System.Int16
D) System.Number

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

10. ………….. function in vb.net is used to convert character code to character.


A) Char
B) Format
C) Convert
D) Chr

11. ………… function in vb.net converts character to character code. 87


A) Chr
B) Val
C) Asc
D) Str
12. ……………. function in vb.net converts string to number data type.
A) Chr
B) Val
C) Asc
D) Str

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. Component object model


2. Common object model
3. Computer oriented model
4. Common oriented model

Long answer questions

1. Write a program to generate a telephone bill. The conditions for the bill generation are

i. calls between 0-100 Free

ii. Calls between 101-200 Rs. 1 per call

iii. Call between 201 – 300 Rs. 2 per call

iv. Calls between 301 onwards Rs. 4 per call

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.

B) Suggested Skill Development Projects/ Assignments


Learners are expected to engage with the following or such similar activities
1. Install . NET and VB
2. Make use of 20 different programs as per contents given in syllabus.
3. Do online course ―Introduction to .NET framework from different institutes.
89
C) Essential and Additional Readings

1. Programming with Microsoft Visual Basic .NET: An Object-Oriented Approach,


Introductory 1st Edition by Michael kedahl (Author), William Newman

2. Beginning VB.NET, Second Edition Matthew Reynolds, Jonathan


Crossland, Richard Blair, Thearon Willis

3. . NET Programming for Beginners Learn ASP .NET Core in a day easily for
Dummies Engr. Michael David

4. Beginner‘s Guide to Visual Basic .NET Programming A Practical Approach to


VB.NET Serhan Yamacli

5. Learn Visual Basic .Net Programming A Practical Approach Ganesh Kumar


(

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:

After completing this unit, the students will be able to:

 Create Form Controls: Textbox, Label, Button, Listbox, Combobox, Checkbox,


 Create Form Controls:Picture Box, Radio Button, Panel, scroll bar, Timer
 Create ListView, TreeView, toolbar, Status Bar, ProgressBar, StatusBar

4.1 GUI Programming:

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.

• Framework for Building Rich Clients


– RAD (Rapid Application Development)
– Rich set of controls
– Data aware
– ActiveX® Support
– Licensing
– Accessibility
– Printing support
– Unicode support
– UI inheritance
The first step is to start a new project and build a form. Open your Visual Studio and select
File->NewProject and select Visual Basic from the New project dialog box and select
Windows Froms Application.

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.

4.3 Introduction to Common Controls

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,

■ Methods cause an object to do something and

■ Events are what happens when an object does something.

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.

■ Syntax: Object.Property = Value


Example: Form1.Caption = ―Hello‖

4.3.2 CONTROL METHODS

A method is a procedure created as a member of a class and they cause an object to do


something. Methods are used to access or manipulate the characteristics of an object or a
variable. There are mainly two categories of methods :

■ 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

4.3.3 CONTROL EVENT

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.

S.No. Name of Control Description

1 Forms The container for all the controls that make up the user
interface.

2 Textbox It represents a windows textbox control. 94


3 Label It represents a windows label.

4 Button It represents a windows button control.

5 ListBox It represents a Windows control to display a list of items.

6 ComboBox It represents a Windows combo box control.

7 RadioButton It enables the user to select a single option from a group of


choices when paired with other RadioButton controls.

8 CheckBox It represents a Windows CheckBox.

9 PictureBox It represents a Windows picture box control for displaying an


image.

10 ScrollBar It Implements the basic functionality of a scroll bar control.

11 DateTimePicker It represents a Windows control that allows the user to select a


date and a time and to display the date and time with a specified
format.

12 ListView It represents a Windows list view control, which displays a


collection of items that can be displayed using one of four
different views.

4.4 CREATING CONTROLS IN VB.NET

 User-interface objects on the form:  etc.

 Labels

 Buttons

 Text boxes

 Menus

 List & combo boxes

 Option buttons
95
 Check boxes
Abstraction:

Like forms, controls are based on classes in the FCL:

 System.Windows.Forms.Label

 System.Windows.Forms.TextBox

 System.Windows.Forms.Button

 Controls are instances of these classes

Who creates all these objects?

 Who is responsible for creating control instances?

 code is auto-generated by Visual Studio

 when form object is created, controls are then created…

96
Naming conventions

 Set control's name via Name property

 A common naming scheme is based on prefixes:

– cmdOK refers to a command button control

– lstNames refers to a list box control

– txtFirstName refers to a text box control

4.5 Text box

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.

 Most commonly used control!

 for displaying text

 for data entry

 Lots of interesting features…

Text box properties

 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

 Do you want multi-line text boxes?

– MultiLine: True allows multiple lines of text

– Lines: array of strings, one for each line in text box

– ScrollBars: none, horizontal, vertical, or both

S. Property Description
No:

1. AcceptsReturn Gets or sets a value indicating whether pressing ENTER in a multiline


TextBox control creates a new line of text in the control or activates
the default button for the form.

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.

4. FontHeight Gets or sets the height of the font of the control.

5. ForeColor Gets or sets the foreground color of the control.

6. Lines Gets or sets the foreground color of the control.

7. Multiline Gets or sets a value indicating whether this is a multiline TextBox


control.

8. PasswordChar Gets or sets the character used to mask characters of a password in a


single-line TextBox control.

9. TextLength Gets the length of text in the control.

`10. Text Gets or sets the current text in the TextBox.

98
Methods of the TextBox Control

S. No: Method Name Description

1. AppendText Appends text to the current text of a text box.

2. Clear Clears all text from the text box control.

3. Copy Copies the current selection in the text box to


the Clipboard.

4. Cut Moves the current selection in the text box to


the Clipboard.

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.

7. ResetText Resets the Text property to its default value.

8. ToString Returns a string that represents the TextBoxBase control.

9. Undo Undoes the last edit operation in the text box.

Text box events

 Interesting events:

– Enter, Leave: occurs on change in focus

– KeyPress: occurs on ascii keypress

– KeyDown, KeyUp: occurs on any key combination

– TextChanged: occurs whenever text is modified

– Validating and Validated

 Validating gives you a chance to cancel on invalid input


99
4.6 Label

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

 For static display of text

 used to label other things on the form


 used to display read-only results
Properties of the Label Control

S. No: Property Description

1. Autosize Gets or sets a value specifying if the control should be


automatically resized to display all its contents.
2. BorderStyle Gets or sets the border style for the control.

3. Font Gets or sets the font of the text displayed by the control.

4. FontHeight Gets or sets the height of the font of the control.


5. ForeColor Gets or sets the foreground color of the control.

6. PreferredHeight Gets the preferred height of the control.

7. PreferredWidth Gets the preferred width of the control.

8. Text Gets or sets the text associated with this control.


10
9. TextAlign Gets or sets the alignment of text in the label. 0
Methods of the Label 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.

3. Select Activates the control.

4. Show Displays the control to the user.

5. ToString Returns a String that contains the name of the control.

Events of the Label Control

S. No: Event Description

1. AutoSizeChanged Occurs when the value of the AutoSize property changes.

2. Click Occurs when the control is clicked.

3. DoubleClick Occurs when the control is double-clicked.

4. GotFocus Occurs when the control receives focus.

5. Leave Occurs when the input focus leaves the control.

6. LostFocus Occurs when the control loses focus.

7. TabIndexChanged Occurs when the TabIndex property value changes.

8. TabStopChanged Occurs when the TabStop property changes.

9. TextChanged Occurs when the Text property value changes.

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

S. No: Properties Description

1. AutoSizeMode Gets or sets the mode by which the Button automatically resizes
itself.

2. BackColor Gets or sets the background color of the control.

3. BackgroundColor Gets or sets the background image displayed in the control.

4. ForeColor Gets or sets the foreground color of the control.

5. Image Gets or sets the image that is displayed on a button control.

6. Location Gets or sets the coordinates of the upper-left corner of the


control relative to the upper-left corner of its container.

7. TabIndex Gets or sets the tab order of the control within its container.

8. Text Gets or sets the text associated with this control. 10


2
Methods of the Button Control

S. No: Method Description

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.

3. Select Activates the control.

4. ToString Returns a String containing the name of the Component, if any.


This method should not be overridden.

Events of the Button Control

S. No: Event Description

1. Click Occurs when the control is clicked.

2. Double Click Occurs when the user double-clicks the Button control.

3. GotFocus Occurs when the control receives focus.

4. TabIndexChanged Occurs when the TabIndex property value changes.

5. TextChanged Occurs when the Text property value changes.

6. Validated Occurs when the control is finished validating.

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;

MessageBox.Show( "Sum = " + k.ToString() )

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.

 Great for displaying / maintaining list of data

 list of strings

 list of objects (list box calls ToString() to display)

10
4
PROPERTIES OF LISTBOX

S.No. Properties Name Description

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.

3 ColumnWidth Gets of sets the width of columns in a multicolumn list box.

4 HorizontalScrollBar Gets or sets the value indicating whether a horizontal scrollbar is


displayed in the list box.

5 ItemHeight Gets or sets the height of an item in the list box.

6 Items Gets the items of 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.

Methods of Listbox Control

S.No. Method Name Description

1 BeginUpdate Prevents the control from drawing until the EndUpdate method
is called, while items are added to the ListBox one at a time.

2 ClearSelected Unselects all items in the ListBox.

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.

6 GetSelected Returns a value indicating whether the specified item is


selected.

7 SetSelected Selects or clears the selection for the specified item in a


ListBox.

8 OnSelectedIndexChanged Raises the SelectedIndexChanged event.

9 OnSelectedValueChanged Raises the SelectedValueChanged event.

Events of ListBox Control

S.No. Name of Event Description

1 Click Occurs when a list box is selected.

2 SelectedIndexChanged Occurs when the SelectedIndex property of a list box


is changed.
10
6
Customer[] customers
.
. // create & fill array with objects...
.
// display customers in list box
foreach (Customer c in customers)
this.listBox1.Items.Add(c)

// display name of selected customer (if any)


Customer c;
c = (Customer) this.listBox1.SelectedItem;
if (c == null)
return;
else
MessageBox.Show(c.Name);

4.9 ComboBox Control

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

S.No. Properties Name Description

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.

3. DataSource Gets or sets the data source for this 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.

8. FlatStyle Gets or sets the appearance of the ComboBox.

9. ItemHeight Gets or sets the height of an item in the combo box.

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.

14. SelectedItem Gets or sets currently selected item in the ComboBox.

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.

Methods of ComboBox Control

S.No. Method Names Description

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.

Events of ComboBox Control

S.No. Event Names Description

1. DropDown Occurs when the drop-down portion of a


combo box is displayed.

2. DropDownClosed Occurs when the drop-down portion of a


combo box is no longer visible.

3. DropDownStyleChanged Occurs when the DropDownStyle property


of the ComboBox has changed.

4. SelectedIndexChanged Occurs when the SelectedIndex property of a


ComboBox control has changed.

5. SelectionChangeCommitted Occurs when the selected item has changed


and the change appears in the combo box.

Public Class OrderYourPizza

Private Sub Type_SelectedIndexChanged(sender As Object, e As EventArgs) Handles


Type.SelectedIndexChanged 10
9
Dim i As Integer

i = Type.SelectedIndex

If Type.SelectedItem = "Vegetarian" Then

FinalOrder.Text += "Type: Vegetarian" + vbNewLine

ElseIf Type.SelectedItem = "NonVegetarian" Then

FinalOrder.Text += "Type: NonVegetarian" + vbNewLine

End If

End Sub

Private Sub Sizep_SelectedIndexChanged(sender As Object, e As EventArgs) Handles


Sizep.SelectedIndexChanged

Dim i As Integer

i = Sizep.SelectedIndex

If Sizep.SelectedItem = "Small" Then

FinalOrder.Text += "Size:Small" + vbNewLine

ElseIf Sizep.SelectedItem = "Medium" Then

FinalOrder.Text += "Size: Medium" + vbNewLine

ElseIf Sizep.SelectedItem = "Large" Then

FinalOrder.Text += "Size: Large" + vbNewLine

End If

End Sub

Private Sub Toppings_SelectedIndexChanged(sender As Object, e As EventArgs) Handles


Toppings.SelectedIndexChanged

Dim i As Integer

i = Toppings.SelectedIndex

For Each Item As Object In Toppings.SelectedItems

FinalOrder.Text += Item.ToString + vbNewLine

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.

4.10 PICTURE BOX

• The PictureBox control is used for displaying images on the form.

• 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

Gets or sets the text for the picture box

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

StrechImage − allows stretching of the image

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.

METHODS OF PICTURE BOX

 ToString

Returns the string that represents the current picture box

 Load: Displays an image in the picture box

 CancelAsync: Cancels an asynchronous image load.

EVENTS OF PICTURE BOX

 Click: Occurs when the control is clicked.

 Enter: Overrides the Control.Enter property.

 KeyPress: Occurs when a key is pressed when the control has focus.

 ForeColorChanged

Occurs when the value of the ForeColor property changes.

 Resize

Occurs when the control is resized.

 SizeChanged

Occurs when the Size property value changes

• TextChanged

Occurs when the value of the Text property changes.

• Leave

Occurs when input focus leaves the PictureBox.

• RightToLeftChanged

Occurs when the value of the RightToLeft property changes.

11
3
4.11 CHECK BOX

• The CheckBox control allows the user to set true/false or yes/no type options.

• The user can select or deselect it.

• When a check box is selected it has the value True,

• when it is cleared, it holds the value False. 11


4
PROPERTIES OF CHECKBOX

 Appearance

Gets or sets a value determining the appearance of the check box

 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

Gets or sets the state of a check box.

• Text

Gets or sets the caption of a check box.

• 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

Raises the CheckedChanged event. 11


5
 OnCheckStateChanged

Raises the CheckStateChanged event.

 OnClick

Raises the OnClick event

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

• The RadioButton control is used to provide a set of mutually exclusive options.

• The user can select one radio button in a group.

• 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

Gets or sets a value determining the appearance of the radio button.

 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

Gets or sets the caption for a radio button.

 Checked

Gets or sets a value indicating whether the control is checked

METHODS OF RADIO BUTTON

 PerformClick

Generates a Click event for the control, simulating a click by a user.

EVENTS OF RADIO BUTTON

 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

 You can define custom height and width of a panel.

12
1
Panels can be used to create multiple pages in a single form

4.14 Scroll BAR

 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

 START : It consists of start event that is triggered by a button/another event

 STOP : It consists of stop event that stops the counter of timer.

 RESTART: It helps restart the timer for a new event.


12
 RESET : It is a function that resets the counter of timer and timer itself. 5
PROGRAM TO Illustrate WORKING OF TIMER

4.16 ListView Control

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

Gets or sets the alignment of items in the control.

2)AutoArrange

Gets or sets whether icons are automatically kept arranged.

3)BackColor

Gets or sets the background color.

4)CheckBoxes

Gets or sets a value indicating whether a check box appears next to each item in the control.

5)CheckedItems

Gets the currently checked items in the control.

6)Columns

Gets the collection of all column headers that appear in the control.

7)Items

Gets a collection containing all items in the control.

8)Sorting

Gets or sets the sort order for items in the control.

9)SelectedItems

Gets the items that are selected in the control.

10)CheckedIndices

Gets the indexes of the currently checked items in the control.

11)SelectedIndices

Gets the indexes of the selected items in the control.


12
7
Methods

1)Clear

Removes all items from the ListView control.

2)To String

Returns a string containing the string representation of the control.

Events

1)ColumnClick

Occurs when a column header is clicked.

2)ItemCheck

Occurs when an item in the control is checked or unchecked.

3)SelectedIndexChanged

Occurs when the selected index is changed.

4)TextChanged

Occurs when the Text property is changed.

Example

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

Dim ListView1 As ListView

ListView1 = New ListView()

ListView1.Location = New Point(10, 10)

ListView1.Size = New Size(150, 150)

Me.Controls.Add(ListView1)

Dim ListItem1 As ListViewItem

ListItem1 = ListView1.Items.Add("Item 1")


12
8
Dim ListItem2 As ListViewItem

ListItem2 = ListView1.Items.Add("Item 2")

Dim ListItem3 As ListViewItem

ListItem3 = ListView1.Items.Add("Item 3")

Dim ListItem4 As ListViewItem

ListItem4 = ListView1.Items.Add("Item 4")

ListView1.View = View.SmallIcon

Me.Text = ―Form 1"

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

Gets or sets the background color for the control.

2)BackgroundImage

Gets or set the background image for the TreeView control.

3)BorderStyle

Gets or sets the border style of the tree view control.

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

Gets or sets the font of the text displayed by the control.


13
0
6)ForeColor

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

Gets or sets the text of the TreeView.

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

Expands all the nodes.

3)GetNodeAt

Gets the node at the specified location.

4)GetNodeCount

Gets the number of tree nodes.

5)Sort

Sorts all the items in the tree view control.

6)ToString

Returns a string containing the name of the control.

13
1
Events

1)AfterCheck: Occurs after the tree node check box is checked.

2)AfterSelect: Occurs after the tree node is selected.

3)BeforeCheck: Occurs before the tree node check box is checked.

4)BeforeSelect: Occurs before the tree node is selected.

5)ItemDrag : Occurs when the user begins dragging a node.

6)NodeMouseClick: Occurs when the user clicks a TreeNode with the mouse.

7)TextChanged: Occurs when the Text property changes.

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

1)BackColor: Gets or sets the background color of the tree node.

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.

7)LastNode: Gets the last child tree node.

8)Name: Gets or sets the name of the tree node.

9)NextNode: Gets the next sibling tree node.

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

1)Collapse: Collapses the tree node.

2)Expand: Expands the tree node.

3)GetNodeCount: Returns the number of child tree nodes.

4)Remove: Removes the current tree node from the tree view control.

5)ToString: Returns a string that represents the current object.

Example

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

Dim TreeView1 As TreeView

TreeView1 = New TreeView()

TreeView1.Location = New Point(10, 10)

TreeView1.Size = New Size(150, 150)

Me.Controls.Add(TreeView1)

TreeView1.Nodes.Clear()

Dim root = New TreeNode("Application")

TreeView1.Nodes.Add(root)

TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 1"))

For loopindex As Integer = 1 To 4

TreeView1.Nodes(0).Nodes(0).Nodes.Add(New _

TreeNode("Sub Project" & Str(loopindex)))

Next loopindex

TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 6"))

For loopindex As Integer = 1 To 3


13
3
TreeView1.Nodes(0).Nodes(1).Nodes.Add(New _

TreeNode("Project File" & Str(loopindex)))

Next loopindex

Me.Text = "tutorialspoint.com"

End Sub

End Class

You can expand the nodes to see the child nodes −

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

Adding a Toolbar to a Form

 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:

 The second of those images is a dropdown list of available ToolStrip options:

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 :

Coding For your Toolbar buttons

 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.

4.19 Status bar

 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

Name Availability Description

It is possible to assign an image to the status


BackgroundImage Read/Write
bar that will be drawn in the background.

This is the collection of panels in the status


Panels Read/Write bar. Use this collection to add and remove
panels.

If you want to display panels, this property


ShowPanels Read/Write
must be set to true.

Text Read/Write Text

 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.

PanelClick Occurs when a panels is clicked.

The StatusBarPanel Class

 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.

 Code for button click on go button

 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

 Print dialog- lets the user set printing options.

 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.

4.21 MDI APPLICATIONS

 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

 Single-document interface applications

 Create one instance of a particular form

 Multiple-document interface (MDI) applications

 Create multiple instances of the same form

 Display those multiple form instances such that they appear inside the region of another form

 Excel is an MDI application, for example

Parent and Child Forms

 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.

CREATING A MDI PROJECT

 Open a new Windows Application in which there is a form named Form1.

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

Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e AsSystem.Even


tArgs)

 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

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e AsSystem.Event


Args) 14
7
 Handles ExitToolStripMenuItem.Click
Me.Close()
'Closing the application
End Sub
End Class

4.22 CREATE A MENU

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

 MenuStrip component is added to a form


 MenuStrip is a container to which ToolStripMenu Items, ToolStripComboBoxes, ToolStripSeparators,
and ToolStripTextBoxes can be added

 Start visual studio.


 On the file menu,click new project.
 Create a new windows application project.
 Click the menustrip control on the menus and toolbar tab of the toolbox and then draw a menu control on
your form.
*the menu strip object doesn‘t appear on your form , but below it. Non-visible objects , such as menus and
timers, are displayed in the IDE in a separate pane named the component tray, and you can select them, set their
properties ,or delete them from this pane*

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.

 (clock menu with two commands)

The Text Property

 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 File menu item that is added is automatically named FileToolStripMenuItem

 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

The MenuStrip Items Collection

 ToolStripMenu Items in the collection can be displayed, reordered, added, deleted using the Items
Collection Editor

ADDING ACCESS KEYS TO MENU COMMAND

 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.

 Set the properties on label


 Autosize-false
 Borderstyle-fixed single
 text – (empty)
 Text align- middle centre
 and resize the label so that
 it is much larger to displat
 date and time
15
2
EDIT THE MENU EVENT PROCEDURES

 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

 Used for grouping menu items according to their purpose

 Visually represented as a bar across the menu

 To create a separator bar, add a new menu item and click on its drop-down arrow

Standards for Windows Menus

 Follow Windows standards for applications

 Include keyboard access keys

 Use standards for shortcut keys, if used

 Place the File menu at left end of menu bar and end File menu with the Exit command

 Help, if included, is placed at right end of menu bar

File Edit View Format Help 15


4
Conclusion : In this Unit, you've seen how to work with Windows forms in creating a desktop application, how
to add and interact with Form controls like Textbox, Label, Button, Listbox, Combobox, Checkbox, Picture
Box, Radio Button, Panel, scroll bar, Timer, ListView, TreeView, toolbar, Status Bar. Students learnt the use of
Dialog Controls, creation and use of MDI applications, Toolbar, Status Bar, creation of custom controls, and
Menus for GUI application development.

B) Progress Check: MCQ’s and long answer question

MCQ’S

Q.1 A GUI

A. uses buttons, menus, and icons

B. should be easy for a user to manipulate

C. stands for Graphic Use Interaction

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.

B. They are the same when the control is first created.

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. bto and cbo B. bto and chb

C. btn and cbo D. btn and chb

Q.4 Which task is accomplished in the Code editor?

A. Adding forms to the project

B. Adding controls to the form

C. Adding controls to the title

D. Adding event procedures to the form


15
5
Q.5 Which statement about objects is true?

A.One class is used to create one object.

B. One class can create many objects.

C.One object is used to create one class.

D.One object can create many classes.

Q.6 Which is not a property of the Common control class?

A. Font B. show

C. ForeColor D. BackColor

Q.7 In event-driven programming an event is generated by:


A. the system B. a user‘s action

C. the program itself D. All of the above

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

D.Windows Form Designer

Answers

Q1. D
Q2. B
Q3. C
Q4. D
Q5. B
Q6. B
Q7. D
Q8. A

Long Answer Questions

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.

Q.4 What is the purpose of VB.NET PictureBox and ProgressBar control?

Q.5 Explain TreeView and ListView control

C) 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.Changing of Font name, FontSize, FontColor, BackColor of Label Control


Q2.Explain properties or methods of these controls:-
TextBox, Label, ComboBox, RadioButton, Button, Timer, PictureBox.

Q3.Explain TreeView and ListView control

Assignment 2

Q.1 ArrayList with example also explain its five methods/properties

Q.2 Write a program to change the font properties(Font name, FontSize, FontColor, BackColor) of

TextBox Control on Click Procedure of Button Control.

15
7
Chapter 5: Object Oriented Features:
Learning Outcomes of the Chapter:

After completing this unit, the students will be able to:

 Understand the concept of Classes and Objects


 Understand Reusability, Constructors
 Familiar with the concepts Inheritance, Overloading, Overriding
 Understand how to Create and Use Namespaces

5.1 OOP(Object Oriented Programming)

 Visual Basic is Object-Oriented Programming Language. Visual Basic .NET supports all features of
OOP like

 Abstraction, Encapsulation, Polymorphism and Inheritance.

 Object Oriented Programming (OOP) is based on a real world interpretation of programming elements.

Abstraction & Encapsulation

 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.

 Ease of fabrication and maintenance.

 Easy redesign and extension.

Disadvantages of OOP

 OOP‘s program design is tricky.

 Need of proper planning & proper design for OOP programming.

 With OOP, classes tend to be overly generalized. 15


8
CLASS

 A class is a way to bind the data describing an entity & its associated functions together.

Public Class <classname>

...

...

End Class

Object Oriented Programming with VB.NET

• 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.

5.2 Classes and Objects

• A class is a representation or a template of common attributes and behaviour of objects.

• Instances of a class are called objects.

Defining and using a Class

Public Class Vehicle

Public companyname as String

Public make as String

Public price as Integer

Public mileage as Integer


15
End Class 9
Public Sub Main()

Dim car as new Vehicle

Dim truck as new Vehicle

car.companyname="Ford"

car.make="Ikon"

End sub

5.3 Properties and Methods

Object

Methods:--govern the behaviour of the object and typically consist of action

statements similar to a function or a procedure

Properties:--denote read-only values that once set cannot be changed and values that can be read as well as
changed.

Using Properties

Public Class Person

...

...

Private agevalue as Integer

Public Property Age() as Integer

Set(ByVal value as Integer)

agevalue=value

End Set

Get

Return agevalue

End Get

End Property
16
... 0
End Class

Demonstrating Properties

Module m

Public Class Person

Public name as String

Public gender as Char

Private age as Integer

Public address as String

Public Property AgeValue( ) as Integer

Set(ByVal value as Integer)

age=value

End Set

Get

Return age

End Get

End property

End class

Public Sub Main()

Dim student as new person

Dim housewife as new person

student.name="Jeremy"

student.gender="M"

student.agevalue=19

System.Console.WriteLine("Student details are")

System.Console.WriteLine(student.name)

16
1
System.Console.WriteLine(student.gender)

System.Console.WriteLine(student.agevalue)

End sub

End module

Types of Properties

Properties are classified into 3 types:

WriteOnly Properties

ReadOnly Properties

ReadWrite Properties

Using Methods

Module m

Public Class Point

Public X as Integer

Public Y as Integer

Public sub Assign()

System.Console.WriteLine("Enter values for point")

x=System.Console.ReadLine( )

y=System.Console.ReadLine( )

End Sub

End Class

Public Sub Main()

Dim P as New Point()

P.Assign( )

System.Console.WriteLine("Point p is")

16
2
System.Console.WriteLine(p.x)

System.Console.WriteLine(p.y)

End Sub

End Module

Using Methods and Properties

Module m

Public Class Person

Public name as String

Public gender as Char

Private age as Integer

Public address as String

Public Property Agevalue() as Integer

Set(ByVal value as Integer)

age=value

End Set

Get

Return age

End Get

End property

Public Sub input()

System.Console.WriteLine("Enter the name, gender and address")

name=System.Console.ReadLine()

gender=System.Console.ReadLine()

address=System.Console.ReadLine()

16
3
End Sub

End Class

Public Sub Main()

Dim student as new Person

Dim housewife as new Person

student.agevalue=19

student.input()

System.Console.WriteLine()

System.Console.WriteLine("Student details are")

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

5.4 Constructors and Destructors

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 Class Point

Public X as Integer

Public Y as Integer
16
4
Public Sub New()

System.Console.WriteLine("This is a constructor")

System.Console.WriteLine("Enter values for point")

x=System.Console.ReadLine()

y=System.Console.ReadLine()

End sub

End class

Public Sub Main()

Dim P as new Point()

System.Console.WriteLine("Point p is")

System.Console.WriteLine(p.x)

System.Console.WriteLine(p.y)

End sub

End module

Destructors

• Written using the Finalize method.

• Normally used for cleanup operations such as releasing or freeing of memory that is no longer
required.

• Called by the system whenever an object is being destroyed.

Overrides Protected Sub Finalize( )

...

...

End sub

16
5
Module m

Public Class Point

Public X as Integer

Public Y as Integer

Public Sub New()

System.Console.WriteLine("This is a constructor")

System.Console.WriteLine("Enter values for point")

x=System.Console.ReadLine()

y=System.Console.ReadLine()

End Sub

Overrides Protected Sub Finalize()

System.Console.WriteLine("This is a destructor executing

since object is now going to be destroyed")

End sub

End class

Public Sub main()

Dim P as new Point()

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.

[Overloads] [Sub <procedure name> | Function <function name> | Property <propertyname]

Factors that cannot be used as a differentiating feature in overloading:

• Modifiers to a procedure (Shared and other such modifiers)

• Modifiers to a parameter (For example, ByVal)

• 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

• Public Overloads Sub area(ByVal r)

• Public Overloads Sub area(ByVal length, ByVal width)

• 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

Sub Max( a as Integer, b as Integer)

Dim c as Integer

c=a+b

System.Console.WriteLine("sum of a and b is " & c)

End Sub

Sub Max(s1 as String, s2 as String)

Dim s3 as String

s3=s1+s2

System.Console.WriteLine("The combined string is " & s3)

End Sub

End Class

Sub Main()

Dim Y as New X()

Y.Max(50,100)

Y.Max("Aptech ", "Limited")

End Sub

End Module

Overloading Constructors

Module M

Class Base

Public Sub New()

16
8
System.Console.WriteLine("Parameterless constructor")

End Sub

Public Sub New(X as Integer)

System.Console.WriteLine("Integer Parameter constructor")

End Sub

Public Sub New(S as String)

System.Console.WriteLine("String Parameter constructor")

End Sub

End Class

Sub Main()

Dim b1 as new Base()

Dim b2 as new Base(10)

Dim b3 as new Base("Hello")

End Sub

End Module

Overloading Properties

Module m

Public Class X

Private addr as string

Private addr2 as string

Overloads Public Property Address() as String

Set(ByVal add as String)

addr=add

End Set

16
9
Get

Return addr

End Get

End property

Overloads Public Property Address(s as String) as String

Set(ByVal add as String)

addr2=add

End Set

Get

Return addr2

End Get

End property

End class

Public Sub Main()

Dim Y as new X()

Dim s as string

System.Console.WriteLine("Enter company address")

Y.address()=System.Console.ReadLine()

System.Console.WriteLine("Enter residence address")

Y.address("residence")=System.Console.ReadLine()

System.Console.WriteLine("The residence address is :")

System.Console.WriteLine(Y.address("residence"))

System.Console.WriteLine("The company address is :")

System.Console.WriteLine(Y.address())

End Sub

17
0
End Module

Inheritance

Module m

Public Class Building

Public Floors as Integer

Public Address as String

End Class

Public Class Apartment

Inherits Building

Public Name

End class

Public Sub Main()

Dim SchoolBuilding as New Building

Dim Flatz as New Apartment

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

Overridable Public Sub Test(a as Integer, b as Integer)

System.Console.WriteLine ("Answer is" & a+b)

End Sub
17
1
End Class

Class Child

Inherits Base

Overrides Public Sub Test (a as Integer, b as Integer)

System.Console.WriteLine ("Answer is" & a*b)

End Sub

End Class

Sub Main()

Dim B as New Base()

Dim C As new Child()

B.Test(10,20)

C.Test(10,20)

End Sub

End Module

MustOverride, MustInherit & Shadows

• 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

Public Sub Test()

End Sub

Public Sub Test(X as Integer)

17
2
End Sub

End Class

Class Child

Inherits Base

Shadows Sub Test(Y as Integer)

End sub

End Class

Sub Main

Dim C as new Child()

‗invalid

'C.Test()

'valid

C.Test(100) ‗ Test procedure of derived class will be

‗called here

End Sub

End Module

NotOverridable and MyBase

NotOverridable:- method or property cannot be overridden

MyBase:--Refers to base class method in a derived class that has overridden methods of the base class.

Module M1

Public Class Animal

Overridable Public Sub Eats()

System.Console.WriteLine("Eats Food")

End sub

End Class

17
3
Public Class Cow

Inherits Animal

Overrides Public Sub Eats()

System.Console.WriteLine("Eats grass")

End sub

Public Sub Eating()

MyBase.Eats()

System.Console.WriteLine("is a herbivorous animal")

End Sub

End class

Demonstrating MyBase

Module M1

Public Class Animal

Overridable Public Sub Eats()

System.Console.WriteLine("Eats Food")

End sub

End Class

Public Class Cow

Inherits Animal

Overrides Public Sub Eats()

System.Console.WriteLine("Eats grass")

End sub

Public Sub Eating()

MyBase.Eats()

System.Console.WriteLine("is a herbivorous animal")

17
4
End Sub

End class

Sub Main()

Dim A as New Animal()

Dim C as New Cow()

C.Eating()

C.Eats()

End Sub

End Module

MyClass keyword:--Assume a base class method is overridden in a derived class.

Later, if we wish to call the base class version, then we must use the MyClass keyword.

Module M1

Public Class Animal

Overridable Public sub Eats()

System.Console.WriteLine("Animal Eats Food")

End sub

Public Sub Eatinghabits()

System.Console.WriteLine("Calling method directly")

Eats()

System.Console.WriteLine("Calling method using MyClass")

MyClass.Eats()

End Sub

End Class

Public Class Cow

17
5
Inherits Animal

Overrides Public Sub Eats()

System.Console.WriteLine("Cow eats grass")

End sub

End class

Sub Main()

Dim C as new Cow()

C.Eats()

C.Eatinghabits()

End Sub

End Module

5.7 Access Modifiers

Access modifier Description

Public Elements of a class are inherited by its derived classes.

Private Elements of a class cannot be inherited by derived classes.

Protected Elements may be used within the derived class but not outside the
derived class

Friend Element is accessible throughout the program in which the class is


defined.

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.

Private: Element can only be used within the current module.


17
6
Static : Static variables are initialized when a function or procedure is called for the first time and
retain the values for all subsequent calls.

Using Static keyword

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

Demonstrating Access Modifiers

Module m

Public Class X

Public J as Integer

Private K as Integer

Protected L as Integer
17
7
Friend M as Integer

Public Sub Test()

L=100

End sub

End class

Public Class Y

Inherits X

Public N as Integer

End class

Public Sub Main()

Dim A as new X()

Dim B as new Y()

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 & Inheritance

 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

Public Sub New()

System.Console.WriteLine("Constructor of Base class")

End Sub

End Class

Class Child

Inherits Base

End Class

Sub Main()

Dim B as New Base()

System.Console.WriteLine("Now creating child class object")

Dim C As New Child()

End Sub

End Module

Inheriting Constructors & Destructors

Module m

Class Base

Public Sub New()

System.Console.WriteLine("Constructor of Base class")

End Sub

Overrides Protected Sub Finalize()


17
9
System.Console.WriteLine("Destructor of Base class")

End Sub

End Class

Class Child

Inherits Base

End Class

Sub Main()

Dim B as New Base()

System.Console.WriteLine("Now creating child class object")

Dim C As new Child()

End Sub

End Module

5.9 Abstract and Final classes

Abstract :--cannot be instantiated or used to create objects.

Final classes :--A final class is a class that cannot be used as a base class.

A class cannot be both abstract and final at the same time.

Module m

MustInherit Class AbsBase

Public Sub Test()

System.Console.WriteLine("Abstract Base class")

End Sub

MustOverride Sub AnotherTest()

End Class

Class Child

18
0
Inherits AbsBase

Overrides Sub AnotherTest()

System.Console.WriteLine("Implementing abstract method")

End sub

End Class

Sub Main()

Dim C as new Child()

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

• Interfaces are similar to classes except that they have no implementation.

• An interface cannot be instantiated.

• It is typically implemented using the Implements keyword.

Defining and Implementing an Interface

Defining an Interface:--

Interface <name>

...

...

End Interface

Implementing an Interface:--

Class <classname>

Implements<interfacename>

...

...

End Class

or

Class <classname>

Implements<interfacename>

...

...

End Class

Creating and using an Interface

Module M
18
2
Public Interface I

Sub First()

Sub Second()

End Interface

Public Class X

Implements I

Sub First() Implements I.First

System.Console.WriteLine("Implementation of first

method")

End sub

Sub Second() Implements I.Second

System.Console.WriteLine(―Implementation of second

method‖)

End Sub

End Class

Public Sub Main()

Dim Y as New X()

Y.First()

Y.Second()

End Sub

End module

Demonstrating Multiple Inheritance

Module M

Public Interface I

18
3
Sub Test()

End Interface

Public Class T

Public Sub Testing()

System.Console.WriteLine("Method Testing")

End Sub

End Class

Public Class X

Inherits T

Implements I

Sub Test() Implements I.Test

System.Console.WriteLine("Implemented method")

End sub

End Class

Public Sub Main()

Dim Y as new X()

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

Syntax: Namespace <name>


18
4
...

...

End Namespace

Creating a Namespace

Namespace Plants

Public Class Shrub

Public Species as string

Public flowering as Boolean

Public sub Print()

System.Console.WriteLine(flowering)

End sub

End Class

End Namespace

Using a Namespace

Module M1

Sub Main()

Dim s as New Plants.Shrub

s.flowering=true

s.print()

End Sub

End Module

Using Imports Statement

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.

D) Progress Check: MCQ’s and long answer question

MCQ’S

Q.1 A ___________ performs invisible tasks even if you write no code.


A. destructor B. constructor

C. function D. private method

Q.2 The ______________________ group classes according to their common services.


A. Namespaces B. inheritance

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

Q.7 The default event handler of TextBox is


A KeyPress
B Changed
C TextChanged
D Validating

Answers

Q9. B
Q10. A
Q11. B
Q12. A
Q13. A
Q14. A
Q15. C

Long Answer Questions

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. 3 What is the difference between Namespace and Assembly?

Q.4 Create function for Factorial/ Prime No/ List of odd and Even no

Q.5 Explain interfaces with example

Q.6 Program to create classes and structures

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

Learning Outcomes of the unit:

After completing this unit/lesson, the students will be able to:

 Explain the ADO architecture


 Identify the similarities and differences between ADO and ADO.NET
 Relate the database to a application
 Use the various functions to perform various tasks with the help of database.
 Make use of crystal Reports.
 Employ the outcomes to create a summary or report.

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.

6.1 Difference between ADO and ADO.NET:

S.No. ADO ADO.NET

It is based on COM (Component It is a CLR (Common Language Runtime)


1. Object Modelling). based library.

It works only when data store is It does not needs active connection to
2. connected. access data from data store.

3. It has feature of locking. It does not have feature of locking.

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

XML integration is not feasible in


5. ADO. XML integration is feasible in ADO.NET.

In ADO, data is stored in binary


6. form. While in this, data is stored in XML.

It allow us to create client side It give us the choice of using w=either


7. cursors only. client side and server side cursors.

It requires SQL JOINs and UNIONs It uses DataRelational objects, for


to combine data from multiple tables combining data from multiple tables
8. in a single result table. without requiring JOINs and UNIONs.

It allows completely non-sequential data


It supports sequential access of rows access in DataSet through collection based
9. in a RecordSet. hierarchy.

6.2 ADO.NET Data Namespaces:

 The System.Data namespace and its five supporting namespaces define the ADO.NET
functionality. L. These namespaces reside in the System.Data.dll assembly.

 The six general ADO.NET namespaces are


(a) System.Data
(b) System.Data.Common
(c) System.Data.OleDb
(d) System.Data.Odbc
(e) System.Data.SqlClient
(f) System.Data.SqlTypes.

 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 namespace is the core namespace of ADO.NET. It consists of the 19


base classes for the ADO.NET architecture. All data providers use these classes. It 0
defines classes that represent tables, columns, rows, and DataSets. Some common
classes from this namespace
are DataView, DataViewManager, DataSet, DataTable, DataRow, DataColumn,
and DataRelation. To use these classes in your applications, you need to add a
reference to the System.Data namespace.

 The System.Data.Common namespace defines common classes. These classes are


base classes for concrete data provider classes. All data providers share these
classes. DBConnection, DataAdapter, DbDataAdaper, DataColumnMapping,
and DataTableMapping are some of the classes defined in this namespace. To use
these classes in your application, you need to add a reference to
the System.Data.Common namespace in your application. Sql, OleDb, and Odbc.

 The System.Data.OleDb namespace defines classes to work with OLE-DB data


sources using .NET OleDb data providers. To work with an OLE-DB data source,
you must have an OleDb provider for that data source. Each data provider component
has a class corresponding to it. These classes start with OleDb, followed by the
component. For example, the OleDbConnection class represents a Connection object.
Some of the common classes of this namespace
are OleDbDataAdapter, OleDbDataReader, OleDbCommand, OleDbCommandBuild
er, OleDbError, OleDbParameter, OleDbPermission, and OleDbTransaction. To use
these classes in your application, you need to add a reference to
the System.Data.OleDb namespace in your application.

 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 System.Data.SqlClient namespaces define Sql .NET data provider classes to


work with SQL Server 7.0 or later databases. Similar to Odbc and OleDb classes, the
classes in this namespace start with Sql, followed by the component. For example,
common classes are SqlConnection, SqlDataAdapter, SqlCommand, SqlDataReader,
and SqlTransaction.
 System.Data.SqlTypes, provides a group of classes representing the specific types
found in SQL Server. Some of these classes
are SqlBinary, SqlMoney, SqlString, SqlInt32, SqlDouble, SqlDateTime,
and SqlNumeric.

6.3 ADO.NET Object Model:


19
 ADO.NET components can be categorized into three categories: 1
 Disconnected
 common or shared
 .NET data providers.

 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-4: The ADO.NET components model

 A data provider is a set of components, such


as Connection, Command, DataAdapter, and DataReader.
 The Connection is the first component that talks to a data source.
The Connection object establishes a connection to a data source and is used
in Command and DataAdapter objects as a connection reference.
 A Command object executes a SQL query and stored procedures to read, add,
update, and delete data in a data source via a DataAdapter.
 The DataAdapter is a bridge between a DataSet and the connection. It
uses Command objects to execute SQL queries and stored procedures.
 All data providers share the ADO.NET common components. These components
represent the data. Some of the common components are DataSet, DataView,
and DataViewManager.
 The DataSet uses XML to store and transfer data between the applications and the
data provider. A DataSet is a set of DataTable objects. A DataTable represents a
database table.
 The DataView and DataViewManager objects provide single or multiple views of
a DataSet. You can attach a DataView or a DataViewManager directly to data-bound
controls such as a DataGrid or a DataList. Other common components
are DataTable, DataRow, DataColumn, and so on.

6.4 The Connection Object


 The Connection object is the first component of ADO.NET.
 A connection sets a link between a data source and ADO.NET. 19
A Connection object sits between a data source and 2
a DataAdapter (via Command). You need to define a data provider and a data
source when you create a connection. With these two, you can also specify the
user ID and password depending on the type of data source.
 Figure 1-5 shows the relationship between a connection, a data source, and
a DataAdapter.

Figure 1-5: The relationship between Connection, DataAdpater, and a data source

 We can also connect a Connection object to a Command object to execute SQL


queries, which you can use to retrieve, add, update, and delete data in a data source.
 Figure 1-6 shows the relationship between the Command and Connection objects.

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.

Figure 1-7: Creating a transaction from a Connection object

 Each data provider has a Connection class. The OleDbConnection, SqlConnection,


and OdbcConnection classes represent the Connection object of the OleDb, Sql, and
Odbc data providers, respectively.

6.5 The Command Object


 The Command object is used to execute SQL queries and stored procedures. We can
execute SQL queries to return data in a DataSet or a DataReader object. To retrieve,
add, update, and delete data, you use SELECT, INSERT, UPDATE,
and DELETE SQL queries.
 A DataAdapter generated using the VS .NET Integrated Development Environment
(IDE) has these queries.
 Figure 1-8 shows the relationship between a DataAdaper and a Command object.

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

Figure 1-9: Creating a DataReader from a Command object

6.6 The Command Builder

 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.

Figure 1-10: The relationship between DataAdapter and CommandBuilder

6.7 The DataAdapter Object

 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.

6.8 DataSet Structure


 A DataSet object falls into the disconnected components category. You can use it with
or without data providers. The DataSet consists of a collection of tables, rows,
columns, and relationships. Figure 1-12 illustrates the relationship between a DataSet
and its contents.

Figure 1-12: The relationship between classes in a DataSet

 A DataSet is a collection of DataTables and DataRelations. All DataTable objects of


a DataSet are accessed through the Tables property, which represents a collection
of DataTable objects.
 The Relations property of a DataSet represents the collection of DataRelation objects
associated with a DataSet.
 A DataTable is a collection of DataRow, DataColumn, and Constraint objects.
The Rows, Columns, and Constraints properties of a DataTable represent a collection
of DataRow, DataColumn, and Constraint objects.
 DataRow, DataColumn, and Constraint are the smallest units of a DataSet, and they
represent a table row, column, and constraint, respectively.
DataSets in DataViews
 Another thing you can do with the contents of DataSets is sort and filter them
using DataViews.
 You can have multiple views of a single DataSet.
 A DataView is a view of your data created according to certain criteria.
Each DataView has a one-to-one mapping to a DataTable in a DataSet.
 For example, say you have three tables in a DataSet: table1, table2, and table3. Using
three different data tables and data views, you can represent this DataSet in three
19
different views. Using sort and filters, you can even sort and filter the data based on
5
some criteria.
 Figure 1-13 shows three different views of a DataSet in the form of three different
data views.

Figure 1-13: The relationship between DataSet and DataView objects

 A DataView can directly attach to data-bound controls such as a DataGrid, DataList,


or a combo box.

6.9 DATABASE CONNECTIVITY

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.

 Click on the Choose Data Source combo box.


 Click on the Add Project Data Source link.

 This opens the Data Source Configuration Wizard.


 Select Database as the data source type

19
8
 Choose DataSet as the database model.

 Choose the connection already set up.

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

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


Dim connection As SqlConnection = New sqlconnection()
connection.ConnectionString = "Data Source=KABIR-DESKTOP; _
Initial Catalog=testDB;Integrated Security=True"
connection.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter _ 20
("select * from Customers", connection) 2
Dim ds As DataSet = New DataSet()
adp.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
End Sub
End Class
 When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window −

 Clicking the Fill button displays the table on the data grid view control −

Creating Table, Columns and Rows


We have discussed that the DataSet components like DataTable, DataColumn and DataRow
allow us to create tables, columns and rows, respectively.
20
The following example demonstrates the concept − 3
Example 3
So far, we have used tables and databases already existing in our computer. In this example,
we will create a table, add columns, rows and data into it and display the table using a
DataGridView object.
Take the following steps −
 Add a DataGridView control and a button in the form.
 Change the text of the button control to 'Fill'.
 Add the following code in the code editor.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub

Private Function CreateDataSet() As DataSet


'creating a DataSet object for tables
Dim dataset As DataSet = New DataSet()
' creating the student table
Dim Students As DataTable = CreateStudentTable()
dataset.Tables.Add(Students)
Return dataset
End Function

Private Function CreateStudentTable() As DataTable


Dim Students As DataTable
Students = New DataTable("Student")
' adding columns
AddNewColumn(Students, "System.Int32", "StudentID")
AddNewColumn(Students, "System.String", "StudentName")
AddNewColumn(Students, "System.String", "StudentCity")
' adding rows
AddNewRow(Students, 1, "Zara Ali", "Kolkata")
AddNewRow(Students, 2, "Shreya Sharma", "Delhi")
AddNewRow(Students, 3, "Rini Mukherjee", "Hyderabad")
AddNewRow(Students, 4, "Sunil Dubey", "Bikaner")
AddNewRow(Students, 5, "Rajat Mishra", "Patna")
Return Students
End Function

Private Sub AddNewColumn(ByRef table As DataTable, _


ByVal columnType As String, ByVal columnName As String)
Dim column As DataColumn = _
table.Columns.Add(columnName, Type.GetType(columnType))
End Sub
20
'adding data into the table 4
Private Sub AddNewRow(ByRef table As DataTable, ByRef id As Integer,_
ByRef name As String, ByRef city As String)
Dim newrow As DataRow = table.NewRow()
newrow("StudentID") = id
newrow("StudentName") = name
newrow("StudentCity") = city
table.Rows.Add(newrow)
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


Dim ds As New DataSet
ds = CreateDataSet()
DataGridView1.DataSource = ds.Tables("Student")
End Sub
End Class
 When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window −

 Clicking the Fill button displays the table on the data grid view control −

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:

 Selecting the data source control


 Selecting a field to display, which is called the data field
 Selecting a field for the value

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

Let us take the following steps:


Step (1) : Create a new website. Add a class named booklist by right clicking on the solution
name in the Solution Explorer and choosing the item 'Class' from the 'Add Item' dialog box.
Name it as booklist.cs. 20
using System; 8
using System.Data;
using System.Configuration;
using System.Linq;

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;

public String Book


{
get
{
return this.bookname;
}
set
{
this.bookname = value;
}
}

public String Author


{
get
{
return this.authorname;
}
set
{
this.authorname = value;
} 20
} 9
}
}
Step (2) : Add four list controls on the page a list box control, a radio button list, a check
box list, and a drop down list and four labels along with these list controls. The page should
look like this in design view:

The source file should look as the following:


<form id="form1" runat="server">
<div>

<table style="width: 559px">


<tr>
<td style="width: 228px; height: 157px;">
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox>
</td>

<td style="height: 157px">


<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>

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

<td style="height: 21px">


</td>
</tr>

<tr>
<td style="width: 228px; height: 21px">
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
</td>

<td style="height: 21px">


<asp:CheckBoxList ID="CheckBoxList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
</td>
</tr>

<tr>
<td style="width: 228px; height: 21px">
<asp:Label ID="lblrdlist" runat="server">
</asp:Label>
</td>

<td style="height: 21px">


<asp:Label ID="lblchklist" runat="server">
</asp:Label>
</td>
</tr>
</table>

</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();
}
}

protected IList createbooklist()


{
ArrayList allbooks = new ArrayList();
booklist bl;

bl = new booklist("UNIX CONCEPTS", "SUMITABHA DAS");


allbooks.Add(bl);

bl = new booklist("PROGRAMMING IN C", "RICHI KERNIGHAN");


allbooks.Add(bl);

bl = new booklist("DATA STRUCTURE", "TANENBAUM");


allbooks.Add(bl);

bl = new booklist("NETWORKING CONCEPTS", "FOROUZAN");


allbooks.Add(bl);

bl = new booklist("PROGRAMMING IN C++", "B. STROUSTROUP");


allbooks.Add(bl);

bl = new booklist("ADVANCED JAVA", "SUMITABHA DAS");


allbooks.Add(bl);

return allbooks;
} 21
2
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.lbllistbox.Text = this.ListBox1.SelectedValue;
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)


{
this.lbldrpdown.Text = this.DropDownList1.SelectedValue;
}

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)


{
this.lblrdlist.Text = this.RadioButtonList1.SelectedValue;
}

protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)


{
this.lblchklist.Text = this.CheckBoxList1.SelectedValue;
}
}
Observe the following:
 The booklist class has two properties: bookname and authorname.
 The createbooklist method is a user defined method that creates an array of booklist
objects named allbooks.
 The Page_Load event handler ensures that a list of books is created. The list is of
IList type, which implements the IEnumerable interface and capable of being bound
to the list controls. The page load event handler binds the IList object 'bklist' with the
list controls. The bookname property is to be displayed and the authorname property
is considered as the value.
 When the page is run, if the user selects a book, its name is selected and displayed by
the list controls whereas the corresponding labels display the author name, which is
the corresponding value for the selected index of the list control.

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

 Select OLE DB ( ADO ) from Create New Connection.

 Select Microsoft OLE DB Provider for SQL Server.


21
6
 Next screen is the SQL Server authentication screen. Select your Sql Server name,
enter userid, password and select your Database Name. Click next, Then the screen
shows OLE DB Property values, leave it as it is, and click finish.

 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

 Put the following source code in the button click event

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.

7.2 Exporting a crystal report:

How to Export Crystal Report 22


0
 Crystal Report can be exported in two ways
1. Using Crystal Viewer Control.
2. Using the method provided in Report Document Object (SDK).

Crystal Report Viewer Control

 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

 To Export to The Report do the following

Export Crystal Report Using Web Application

Export Crystal Report in Web application

1. Run your Crystal Report Project.


2. Select the Export Report button at the top Left Corner.
3. From the File Format Drop drown select appropriate format.
4. From Page Range Option Select All Pages
If you want print selected pages choose Select Pages and enter the from and to page
No. Note that some of the file formats has this feature disabled
5. Click on Export.
6. File is downloaded.

22
1
Export Crystal Report Using Windows Application

Export Crystal Report in Windows Application

1. Run your Crystal Report Project


2. Select the Export Report button at the top Left Corner
3. From the Save as Drop drown select appropriate format
4. Note that Page Range option is not provided in the windows version of Crystal Report
Viewer Control
5. In File Name Option enter the name of the file
6. Click on Save

 Export Crystal Report Using Report Document (SDK)


 Another way to Export crystal report is using the Methods provided in Report
Document object. This option gives us the most flexibility when comes to exporting
the report.

 ExportToDisk
 Use this option to export the report to disk. Method has following Option

public virtual void ExportToDisk (ExportFormatType formatType, string fileName);

 The above function takes two parameters. formatType and fileName


formatType

 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.

C) Progress Check: MCQ’s and long answer question

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

2. Point out the correct statement.


a) Using the System.Data.SqlClient, you can fill a memory-resident DataSet that you can
use to query and update the database
b) System.Data.SqlClient includes a tabular data stream (TDS) parser to communicate
directly with SQL Server
c) SqlBulkCopyColumnMapping lets you efficiently bulk load a SQL Server table with
data from another source
d) None of the mentioned

3. Valid Code for Creating a SqlConnection Object would be ____________


a) SqlConnection conn = NEW SqlConnection(
"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
b) SqlConnect conn = NEW SqlConnection(

"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");


c)SqlConnection conn = NEW SqlConnect(

"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");


d) All 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‖

5.Point out the wrong statement.


a) The goal of dotConnect for SQL Server is to enable developers to maintain database
applications
b) dotConnect for SQL Server combines connected and disconnected data access models in
single SqlDataTable component
c) dotConnect for SQL Server supports new ADO.NET features and technologies as soon as
they are released
d) None of the mentioned

6. Which of the following is enumeration for ADO.net with SQL Server?


a) SqlInfo
b) SqlBulkCopyOptions
c) SqlNotification
d) All of the mentioned

7. Syntax for closing and opening the connection in ADO.net is _______________


a) sqlConn.Open() and sqlConn.close()
b) sqlConn.open() and sqlConn.Close()
c) sqlConn.Open() and sqlConn.Close()
d) none of the mentioned

8. The main features of dotConnect for SQL Server includes ___________


a) Extra data binding capabilities
b) Ability of monitoring query execution
c) Supports the latest versions of SQL Server
d) All of the mentioned

10. __________object is used to fill a DataSet/DataTable with query results in ADO.net.


a) DataReader
b) Dataset
c) DataAdapter
d) DataTables

11. How can you burst crystal reports by E-mail?

a. Using a PDF tool


b. Using Crystal Reports Scheduler such as CRD
c. Data driven publishing method
d. All of the above

12. What are the disadvantages Of Crystal Reports?

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

14. What all new features available in SAP Crystal?

A. Streamlines report design


B. Improvement to data sources
C. Mobile and viewer support
D. All of these

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

Long Question Answers

Q1. What are the main differences between classic ADO and ADO.NET?

These are the main differences between ADO and ADO.NET:


ADO 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 supports mostly connection oriented models. It works in disconnected manners.

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

The Data reader is read-only, forward only. It is much It is comparatively slower.


faster than data adopter.

Data reader facilitates you to open and close connection If you use data adopter, the
explicitly. connection is automatically open and
closed.

Data reader makes a connection to the database to Data adopter is disconnected.


operate on data.

Q3. What are the different ADO.NET Namespaces?

A list of ADO.NET Namespaces:

Index Namespaces Description

1) System.Data It contains the definition for columns, relations, tables,


database, rows, views, and constraints.

2) System.Data.SqlClient It contains the classes that are used to connect to a


Microsoft SQL Server database such as SqlCommand,
SqlConnection, SqlDataAdapter.

3) System.Data.Odbc It contains classes required to connect to most Odbc


Drivers. These classes include OdbcCommand,
OdbcConnection.

4) System.Data.OracleClient It contains classes such as OracleConnection,


OracleCommand required to connect to an Oracle database.

Q4. What is the difference between DataReader and DataSet?

A list of differences between DataReader and DataSet:

Index DataReader DataSet


22
6
1) Forward only. Loop through the DataSet.

2) Connected recordset. Disconnected recordset.

3) Single table involved. Multiple tables involved.

4) No relationship required. A Relationship between tables maintained.

5) No XML storage. Can be stored as XML.

6) Occupies less memory. Occupies more memory.

7) Read-only Can do addition /Updation and deletion

Q5. Explain what is Crystal Reports?

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?

To connect crystal report to the databases, there are two ways

 Use crystal report built in query


 Use the tool "Crystal SQL Designer" given by crystal report

D) Suggested Skill Development Projects/Assignments


Learners are expected to engage with any two of the following or such similar activities

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.

Essential and AdditionalReadings


1. Visual Basic 2010 programming Black Book, by Kogent Learning Solutions, Wiley
India
2. Visual Basic 2010 Step By Step, Michael Halvorson, PHI
E) References
1. Mastering Microsoft Visual Basic 2010, Evangelos Petroutsos, Wiley Publications
2. Beginning Visual Basic 2010 (Wrox)

22
8

You might also like