You are on page 1of 146

VB.

NET NOTES

PREPARED BY
MRS.S.JASMINE PONMARY
2

SYLLABUS
UNIT I
VB.NET 2005 Training: The .NET Framework Architecture Part
2-Introducing Windows Forms- Implementing Class Library Object in
VB.NET 2005 -Introduction and Implementing Inheritance in VB.NET
2005- Visual Studio.NET Namespaces.
UNIT II
Windows Designing a Form using Forms Designer Window-Exploring
the Forms Designer generated code-Using Application Class and
Message Class-Setting and Adding Properties to a Windows Form -
Event Handling
In Visual Basic .NET 2005.
UNIT III
Building graphical interface elements-Adding Controls -Common
Controls and Handling Control Events-Dialog Boxes in Visual Basic
.NET 2005 -Common Windows Forms Controls
Section-DomainUpDown and NumericUpDown -Creating Menu and
Menu Items-Creating Multiple-Document Interface (MDI) Applications
Validation-Exceptions.
UNIT IV
Creating and Managing Components Section-Creating and Managing
.NET Assemblies-Simple Data Binding-Complex Data Binding-Using
the Data Form Wizard-Access and Manipulate Data - The ADO .NET
Object Model-Access and Manipulate Data - Using DataSets-Using
XML Data.
UNIT V
Finding and Sorting Data in DataSets-Editing Data With ADO .NET-Web
Services - SOAP, WSDL, Disco and UDDI-Instantiating - Invoking Web
Services, Creating Proxy Classes with WSDL-Creating Web Service
Project.

VB.NET 2005 Training


3
Visual Basic (VB) is a programming language based on the original DOS language called
BASIC (Beginners’ All-purpose Symbolic Instruction Code). VB.NET 2005, an offshoot of Visual
Basic, is an object-oriented programming language based on VB that is implemented using the
Microsoft .NET framework. The basic syntax of the Visual Basic language remains unchanged in
VB.NET 2005, but includes additional features such as structured exception handling and short
circuited expressions to enhance the infrastructure of the programming language.
Developers have found VB.NET to be controversial as some of the software and
developmental changes clash with the original language within VB and have caused compatibility
issues. Visual Studio .NET is the predominant integrated development environment (IDE) that
VB.NET developers employ.
Visual Basic programmers supporting VB.NET indicate that language constructs and user
interface features in the newer system have caused programming issues within the original VB
system. Developers using VB.NET recognize that the upgraded VB system incorporates
contemporary object oriented programming paradigms in a more stable environment than was
originally thought possible.
Visual Basic .NET is a programming language that can be used to create winforms or web
app applications and create programming based in any object-oriented programming language
(OOP), ADO.NET, Multithreading or Windows Services. VB.NET programming utilizes concepts
connected to string encryption, forms inheritance, regular expressions and deployment.

The .NET Framework Architecture


The .NET Framework is a software development framework developed by
Microsoft that provides a common programming platform for the development of
applications (such as websites) running on different operating systems (such as
Windows). It was originally released with Microsoft’s first version of its Windows
operating system, Windows 3.0, in 1993 and has undergone many revisions
since then. The .NET Framework consists of a wide range of components that
can be used to build applications for any computer platform. It includes the core
.NET Framework API, which is the set of classes that provides the basic building
blocks for applications; several other APIs (such as the extensible Markup
Language [XML]) that are designed to support web technologies; and tools such
as Visual Studio, which is an integrated development environment (IDE) that is
designed to make it easy to create, debug, and test applications. The .NET
Framework enables developers to share code between applications running on
different platforms or on the same platform. For this reason, it is also sometimes
called “shared code platform” or “cross-platform development”.
The architecture of the .Net framework focuses on two main things: The first of
these is that the framework code is largely independent of the language in which
it is written. For example, a framework written in C# can contain calls to libraries
written in C++, as well as to libraries written in other programming languages.
This allows .Net programs to be ported to a wide variety of platforms. The second
main goal of the .Net framework is that it should be easy to adopt. This means
that the framework should be designed in a way that makes it easy to incorporate
new features and new functionality into an existing program. The framework
should also be designed in a way that makes it easy to port the program to a
different platform or make the program run on a different type of computer. The
4

.Net framework has been built in a way that makes it easy for programmers to
build new features into their programs. It has also been built in a way that
makes it easy to extend the program with new features.

Common Language Specification


Common Language Specification helps in easy creation of the apps and
software. It is the standardized set of rules and guidelines that are followed to
develop software in one language. It helps in reducing the complexity of the apps
and software. Common Language Specification also helps in reduction of cost. It
helps in reducing the development time and cost.
Common Language Infrastructure
The language-independent nature of the CLI makes it easier to transition your
app across different platforms. It also streamlines the process of migrating an
app from one platform to another because it has a standard code structure, a
5

single standard library, and as a result, a single standard application


deployment process across all platforms. The CLI is an app development
framework that is language-independent. Therefore, developers don’t have to
worry about changing the language or syntax of their source code when
switching from one platform to another.
The CLI has the following key benefits:
● In case the application tries to update some records from the database, but
there is no connection to the database. In case the application tries to
remove some records from the database, but the connection to the
database becomes invalid. These are the various types of application
errors. Now, if we want to handle such errors in a better way, then we have
to use appropriate constructions in the code. For example, to handle such
exceptions, we can use try/catch constructions in the code.
● All the objects that are no longer in the scope of the application and are not
in use. For example, if the application completes its tasks on a file, and
then that file is deleted from the system, then the file handle may not be
used. When the application completes its tasks on a database connection,
and that connection is closed, then the connection may no longer be used.
All the applications have some operations that are in progress. When the
application completes its tasks on some objects, then those objects may
no longer be needed. An example of this is a file that is no longer needed
and that is then deleted from the system, then the file handle may no
longer be used.
● The second level includes the programming languages VB.Net and C#,
which are among the most used.
● It is a good practice to have one code base to compile all the code. If you
are working on multiple projects, then you may end up with multiple
compilations. If you are working with multiple programming languages then
you need to have multiple compilers. There are scenarios where it may be
difficult to compile all the files. For e.g., if your project has VB.Net, C# and
XAML files, then it may be difficult to compile all the files.
● Debugger is another important part of the development team. You need to
have one debugger which can work on all the languages. If you do not
have one debugger which works with all the languages then you may end
up in confusion while debugging the project. For e.g., if you have a VB.Net
project and want to debug it with XAML debugger then it will not work. So
you need to have one debugger which will work with all the languages.
● CLI is a low-level programming language running atop the net framework.
It’s the most common way to develop and run .NET applications. The CLI
is a Command Line Interface that is used to launch an application or script.
You’ll find it under the start menu of your computer. It can be used to
launch any .NET application. It will launch the application in that same
6

console. It’s possible to run any other programming language from the
CLI with the help of a package.

Common Type Specification


A language supporting multiple data types is known as a common type system.
In the example, .NET types are used as an example.
Common Language Runtime
The common language runtime is a component of the .NET framework, and it is
included during the installation of the framework. It is distributed as a part of the
IIS (Internet Information Services) server. When you install the IIS server, the
common language runtime is automatically installed. In any case, you can install
it separately. All programming languages that support the common language
runtime are supported. In any case, C#, VB, and IronPython are the most
commonly used programming languages. In addition, the common language
runtime is available for ASP.NET and Windows applications.
Features of .Net Framework
The .Net framework has several advantages in terms of operating smoothly.
These advantages include the following;
● In other systems, the programmer has to manage memory manually. The
programmer has to monitor the heap and release it when there are no
longer any references. In .NET apps, the CLR handles a range of
resources for the application, including memory. The language allows
programmers to focus on distributing and managing objects’ lifetimes. In
7

.NET apps, the CLR provides a number of services. Those resources


that the program doesn’t need while running are handled by the .Net
framework. This is followed through a process called the “Garbage
Collector”. The garbage collector runs alongside the framework. It screens
all the files, programs, and other items at regular intervals and eventually
frees or releases them.
● It is possible to use the type system of any .NET language in a type-safe
manner. For example, it is possible to use the type system of C# in
ASP.NET MVC. This allows the use of type-safe annotations and improves
the developer experience significantly. It is possible to use the type system
of C# in ASP.NET MVC. This allows the use of type-safe annotations and
improves the developer experience significantly. In addition to this, the
framework type system also defines many other types such as structs,
enums, delegates, interfaces, events, and other custom types. It is
possible to define new types by using a language-independent language
like XML, JSON, or YAML. In addition to this, the framework type system
also defines many other types such as structs, enums, delegates,
interfaces, events, and other custom types. It is possible to define new
types by using a language-independent language like XML, JSON, or
YAMS.
● Extensive class libraries can be found in the System.Data. Data access is
one of the most common tasks that programs must accomplish. When data
needs to be accessed, the data must be moved from one location to
another. To do this, a data transfer occurs. Data access can be thought of
as a puzzle. To access data, data must be moved from one location to
another. There are several ways to accomplish this. The first and most
common way is to use data. To accomplish this, programs use libraries that
can be found in the .NET Framework Class Library (FCL). These libraries
make common tasks easy to perform.
● Interoperability allows developers to test their apps across a wide range of
different devices without the hassle of upgrading their codebase. Besides
that, the Microsoft Graph API is extremely stable and reliable. In addition,
the backend of this platform is well-designed, and it works with a variety of
different technologies. This makes it very easy to integrate with other
services, such as databases and other applications. The development
process is also very smooth on this framework. If a developer uses the
Code Springs online tool to generate a code skeleton, then it will be very
easy to start working on the app.
● For example, Microsoft has indicated that it is open to the idea of an app
that runs on the Android operating system. Microsoft has also stated that it
is open to the idea of creating apps that run on the web. Microsoft has
even indicated that it is exploring the idea of an app that runs on a
8

blockchain. Microsoft’s vision for cross-platform app development has


the potential to reach a much larger audience of software developers.
On the other hand, with cross-platform app development, it is possible for
Microsoft to reach a much wider range of Windows users.
● Every app is given its own security system. The system can be configured
or reconfigured as required, depending on the needs of the app. The
system of the platform is its most valuable asset. Every app can choose
from a range of security systems and CMS. The security system for each
app can be configured and reconfigured as required, depending on the
needs of the app. The .NET framework has a good security system. Every
app can express itself in a straightforward and comprehensive way in
terms of security. Every security system is designed to enable users to
access the code or the running programme. It is also possible to validate
and confirm apps via the system.
● If you upgrade your application to a new version, you do not need to
manually update all the client machines. The package that was distributed
to them will still be available. So, there is no need to distribute the new
package to all the client systems. The .Net framework also simplifies the
process of testing your application. You do not have to keep multiple
versions of the application. The installation package is the only thing that
needs to be updated. In addition, you do not have to manually update the
installation package on all the client machines.
● You can also set the system retry timeout to improve the reliability of
socket communication. The System.Net.Framework.Net framework now
supports the exchange of common types via the
System.Runtime.Remoting.Channels.Tcp class. This enables the setup of
an association of the cached objects via Tcp. This may increase the
execution of network load-balancing by remote clusters by facilitating the
association of cached objects via Tcp. You can also set the system retry
timeout to improve the reliability of socket communication.
● A component is a reusable software component that can be used in a
variety of ways. It can be used within an app, shared across an app, or
used in other apps. It can also be used within a component as a data
object, a configuration object, or as a class object. Depending on how it is
used, it can be thought of as either a component, a plug-in, or even a
feature. In the world of enterprise software development, there is often a
need to create apps that can be extended by different vendors, suppliers,
and providers, to deliver new and different functionality. Extensibility is a
key differentiator between enterprise and consumer apps. Enterprise apps
are often built using frameworks and components to help reduce the app’s
dependencies on other teams.
9

● The .Net Framework version 4 has native support for asynchronous


programming. This means that an application may start another task in
the background while it is still working. The task may be completed at any
time, or only when the background task is completed. Running code on
different threads makes an application more scalable. For example, an
item in the application may need to be processed by an external
component on another server. The component may only retrieve data
when it is active, so the application does not have to be blocked while
waiting for the component to process its data.
● Windows is the most popular OS, and it has a wide variety of input
devices, such as mice, keyboards, and touchscreens. Windows OS comes
with support for many input types, such as mouse, touch, and keyboard.
Windows OS also supports many different display types, such as monitors,
projectors, and TVs. As mentioned earlier, Windows Store apps are
designed to be used on a particular form factor and utilize the power of the
Windows OS. Windows Store apps work on Windows 10 devices, such as
laptops, tablets, and phones. Windows Store apps do not come with
support for other input types, such as VR devices, game controllers, or
other form factors.
Advantages of .NET Framework Architecture
The major advantages of this wonderful framework are listed below.
● The .Net framework has been designed in such a way that it provides a
high level of security. It is important to note that this framework has been
optimized in such a way that it runs quickly. In addition to this, it allows the
user to handle a large number of data types. It is also important to note
that the .Net framework helps in reducing costs. It is because of this
reason that developers are increasingly preferring this framework.
● You can edit website pages without fear of breaking them. You can also
publish new content on your site easily. The updated website pages can be
viewed immediately. This is because the source code is posted on the
server. There is no need to copy-paste the source code. You can simply
access the source code on the web server. This makes the process of
maintaining your website much easier. If you want to publish different
content on your site, you do not need to copy-paste the source code again
and again. You can simply publish new content on the server without any
fear of breaking any existing pages. In addition, you do not need to create
new content every time you want to publish something new.
● With .NET, the app is not only faster but also more secure. It is a complete
package that can be used for both server-side and client-side
development. It is open-source and can be used by anyone. There is no
license or cost to use it. With .NET, you can add features such as voice
recognition, facial recognition, and even handwriting recognition. You can
10

also count on end-to-end encryption and authentication. This framework


also has a robust data storage and management system.
● The platform is built in such a way that the developer does not have to
worry about the nitty-gritty of the backend. The backend is set up by a
developer who knows the system, not by an automated tool. Form
submission is handled by the browser, so there are no network bottlenecks
like there are with other technologies. The .NET platform can also be used
to build a variety of mobile apps, so your data and information needs don’t
have to be limited to one device.
● The process of creating an application is very time-consuming, and
developers do not want to spend their time on it. With the help of an
automated tool, the process of creating an app becomes much easier and
faster. An automated tool offers a set of features that developers can use
to create an app with less effort.
● When a project comes up, it is easy to create a new one. Prior to
submitting a request, a checklist may be created. This may include
information like the project, the deadline, the person who will review the
request, and so on. Once a request is approved, it goes live for the users.
Users may monitor the status of the project from the dashboard. The app
also allows prioritization of the requests. It is very easy to change the
priority of any request.
● When the code is compiled and executed, the platform will trace the flow of
the code and detect any issues. As a result, the issues will be handled
according to the best practices. The platform will also detect any massive
code changes to avoid any issues. After correcting the code, it will be
restarted automatically to trace the flow of the code again. This process will
continue until the platform does not find any issues. In addition, the team
will receive notifications when making changes to the code. The members
of the team will receive detailed information about the code changes,
including their reasons. They will be able to understand the code changes,
fix them, and discard them if necessary.

Introducing Windows Forms


Let's start with creating a Window Forms Application by following the following
steps in Microsoft Visual Studio - File → New Project → Windows Forms Applications
Finally, select OK, Microsoft Visual Studio creates your project and displays the
following window Form with a name Form1.
11

Visual Basic Form is the container for all the controls that make up the user
interface. Every window you see in a running visual basic application is a form, thus
the terms form and window describe the same entity. Visual Studio creates a
default form for you when you create a Windows Forms Application.
Every form will have title bar on which the form's caption is displayed and there will
be buttons to close, maximize and minimize the form shown below
12

If you click the icon on the top left corner, it opens the control menu, which
contains the various commands to control the form like to move control from one
place to another place, to maximize or minimize the form or to close the form.
Form Properties
Following table lists down various important properties related to a form. These
properties can be set or read during application execution. You can refer to
Microsoft documentation for a complete list of properties associated with a Form
control −
S.N Properties Description

1 AcceptButton The button that's automatically activated


when you press Enter, no matter which
control has the focus at the time. Usually the
OK button on a form is set as an
AcceptButton for a form.

2 CancelButton The button that's automatically activated


when you hit the Esc key.
Usually, the Cancel button on a form is set
as CancelButton for a form.
13

3 AutoScale This Boolean property determines whether


the controls you place on the form are
automatically scaled to the height of the
current font. The default value of this
property is True. This is a property of the
form, but it affects the controls on the form.

4 AutoScroll This Boolean property indicates whether


scroll bars will be automatically attached to
the form if it is resized to a point that not all
its controls are visible.

5 AutoScrollMinSize This property lets you specify the minimum


size of the form, before the scroll bars are
attached.

6 AutoScrollPosition The AutoScrollPosition is the number of


pixels by which the two scroll bars were
displaced from their initial locations.

7 BackColor Sets the form background color.


14

8 BorderStyle The BorderStyle property determines the


style of the form's border and the
appearance of the form −
​ None − Borderless window that can't
be resized.
​ Sizable − This is the default value
and will be used for a resizable
window that's used for displaying
regular forms.
​ Fixed3D − Window with a visible
border, "raised" relative to the main
area. In this case, windows can't be
resized.
​ FixedDialog − A fixed window, used
to create dialog boxes.
​ FixedSingle − A fixed window with a
single line border.
​ FixedToolWindow − A fixed window
with a Close button only. It looks like
the toolbar displayed by the drawing
and imaging applications.
​ SizableToolWindow − Same as the
FixedToolWindow but resizable. In
addition, its caption font is smaller
than the usual.

9 ControlBox By default, this property is True and you can


set it to False to hide the icon and disable
the Control menu.

10 Enabled If True, allows the form to respond to mouse


and keyboard events; if False, disables form.

11 Font This property specify font type, style, size

12 HelpButton Determines whether a Help button should be


displayed in the caption box of the form.
15

13 Height This is the height of the Form in pixels.

14 MinimizeBox By default, this property is True and you can


set it to False to hide the Minimize button on
the title bar.

15 MaximizeBox By default, this property is True and you can


set it to False to hide the Maximize button on
the title bar.

16 MinimumSize This specifies the minimum height and width


of the window you can minimize.

17 MaximumSize This specifies the maximum height and width


of the window you maximize.

18 Name This is the actual name of the form.

19 StartPosition This property determines the initial position


of the form when it's first displayed. It will
have any of the following values −
​ CenterParent − The form is centered
in the area of its parent form.
​ CenterScreen − The form is centered
on the monitor.
​ Manual − The location and size of the
form will determine its starting
position.
​ WindowsDefaultBounds − The form
is positioned at the default location
and size determined by Windows.
​ WindowsDefaultLocation − The
form is positioned at the Windows
default location and has the
dimensions you've set at design time.

20 Text The text, which will appear at the title bar of


the form.
16

21 Top, Left These two properties set or return the


coordinates of the form's top-left corner in
pixels.

22 TopMost This property is a True/False value that lets


you specify whether the form will remain on
top of all other forms in your application. Its
default property is False.

23 Width This is the width of the form in pixels.

Form Methods
The following are some of the commonly used methods of the Form class. You can
refer to Microsoft documentation for a complete list of methods associated with
forms control −
Sr.No. Method Name & Description

1 Activate
Activates the form and gives it focus.

2 ActivateMdiChild
Activates the MDI child of a form.

3 AddOwnedForm
Adds an owned form to this form.

4 BringToFront
Brings the control to the front of the z-order.

5 CenterToParent
Centers the position of the form within the bounds of the parent
form.

6 CenterToScreen
Centers the form on the current screen.

7 Close
Closes the form.

8 Contains
Retrieves a value indicating whether the specified control is a child
of the control.

9 Focus
Sets input focus to the control.
17

10 Hide
Conceals the control from the user.

11 Refresh
Forces the control to invalidate its client area and immediately
redraw itself and any child controls.

12 Scale(SizeF)
Scales the control and all child controls by the specified scaling
factor.

13 ScaleControl
Scales the location, size, padding, and margin of a control.

14 ScaleCore
Performs scaling of the form.

15 Select
Activates the control.

16 SendToBack
Sends the control to the back of the z-order.

17 SetAutoScrollMargin
Sets the size of the auto-scroll margins.

18 SetDesktopBounds
Sets the bounds of the form in desktop coordinates.

19 SetDesktopLocation
Sets the location of the form in desktop coordinates.

20 SetDisplayRectLocation
Positions the display window to the specified value.

21 Show
Displays the control to the user.

22 ShowDialog
Shows the form as a modal dialog box.

Form Events
Following table lists down various important events related to a form. You can refer
to Microsoft documentation for a complete list of events associated with forms
control −
Sr.No. Event Description
18

1 Activated Occurs when the form is activated in


code or by the user.

2 Click Occurs when the form is clicked.

3 Closed Occurs before the form is closed.

4 Closing Occurs when the form is closing.

5 DoubleClick Occurs when the form control is


double-clicked.

6 DragDrop Occurs when a drag-and-drop operation


is completed.

7 Enter Occurs when the form is entered.

8 GotFocus Occurs when the form control receives


focus.

9 HelpButtonClicked Occurs when the Help button is clicked.

10 KeyDown Occurs when a key is pressed while the


form has focus.

11 KeyPress Occurs when a key is pressed while the


form has focus.

12 KeyUp Occurs when a key is released while the


form has focus.

13 Load Occurs before a form is displayed for the


first time.

14 LostFocus Occurs when the form loses focus.

15 MouseDown Occurs when the mouse pointer is over


the form and a mouse button is pressed.

16 MouseEnter Occurs when the mouse pointer enters


the form.

17 MouseHover Occurs when the mouse pointer rests on


the form.
19

18 MouseLeave Occurs when the mouse pointer leaves


the form.

19 MouseMove Occurs when the mouse pointer is moved


over the form.

20 MouseUp Occurs when the mouse pointer is over


the form and a mouse button is released.

21 MouseWheel Occurs when the mouse wheel moves


while the control has focus.

22 Move Occurs when the form is moved.

23 Resize Occurs when the control is resized.

24 Scroll Occurs when the user or code scrolls


through the client area.

25 Shown Occurs whenever the form is first


displayed.

26 VisibleChanged Occurs when the Visible property value


changes.

Implementing Class Library Object in VB.NET 2005


.Net Framework Class Library
The FCL is part of the Common Language Runtime. It is loaded when the
program starts and unloaded when the program ends. Through this loading and
unloading process, the CLR is able to locate and load the FCL into memory when
it is required. This loading and unloading process is also known as “Dependency
Injection”. Dependency injection is the process by which the CLR loads the FCL
when it is required and unloads it when it is not required anymore. Dependency
injection is controlled by the FCL. When the CLR needs to load the FCL, it does
so. When the CLR does not need to load the FCL anymore, it unloads it. In other
words, the CLR controls when the FCL is loaded and unloaded. The CLI is the
intermediary language used to generate the native code for the platform being
targeted. The generated code is optimized to run on the native platform. In some
cases, one needs to transfer data between two different platforms. In such cases,
one needs to use a low-level language, such as C++, to transfer data between
two different platforms. The data transfer process is a low-level language
process. File-processing libraries offer such functions and are used to transfer
data between two different platforms.
20

Class: Classical Object Oriented Concepts explain a class as a cookie cutter. A class allows
you to create objects of the class. As a programmer you define a class with data fields,
properties, methods and events. Then you can create objects based on that class that have
state (fields, properties) and behavior (methods, events). A class can be considered as a
specification of how the object of the class should look like and behave.
Creating a Class Library project
1. On the File menu, select New Project.
2. On the Templates pane, in the New Project dialog box, click Class Library.
3. In the Name box, type DemoClass1 and then click OK.
4. A new Class Library project opens, and the Code Editor displays the Class module
Class1.vb.
5. In the Solution Explorer, right-click Class1.vb and select Rename, and then change the
name to DemoClass1.vb.
6. Note that the name in the Code Editor also changed to DemoClass.vb.
7. On the File menu, select Save All.
8. In the Save Project dialog box, click Save.

class library defines types and methods that are called by an application. If the library
targets .NET Standard 2.0, it can be called by any .NET implementation (including .NET
Framework) that supports .NET Standard 2.0. If the library targets .NET 8, it can be
called by any application that targets .NET 8. This tutorial shows how to target .NET 8.
Create a class library project
1. Add a new .NET class library project named "StringLibrary" to the solution.
a. Right-click on the solution in Solution Explorer and select Add >
New Project.
21

b. On the Add a new project page, enter library in the search box.
Choose C# or Visual Basic from the Language list, and then
choose All platforms from the Platform list. Choose the Class
Library template, and then choose Next.
c. On the Configure your new project page, enter StringLibrary in the
Project name box, and then choose Next.
d. On the Additional information page, select .NET 8 (Preview), and
then choose Create.
2. Check to make sure that the library targets the correct version of .NET.
Right-click on the library project in Solution Explorer, and then select
Properties. The Target Framework text box shows that the project targets
.NET 7.0.
3. If you're using Visual Basic, clear the text in the Root namespace text box.

For each project, Visual Basic automatically creates a namespace that


corresponds to the project name. In this tutorial, you define a top-level
namespace by using the namespace keyword in the code file.
4. Replace the code in the code window for Class1.cs or Class1.vb with the
following code, and save the file. If the language you want to use isn't
shown, change the language selector at the top of the page.

Introduction and Implementing Inheritance in VB.NET 2005


Visual Basic developers had wanted inheritance for what seems like decades. The
feature finally made it into VB.NET, making VB.NET an official object-oriented
language.Inheritance is an abstraction for sharing similarities among classes
while preserving their differences.
Inheritance One of the most important concepts in object-oriented programming
is that of inheritance. Inheritance allows us to define a class in terms of another
class which makes it easier to create and maintain an application. This also
provides an opportunity to reuse the code functionality and fast implementation
time. When creating a class, instead of writing completely new data members
and member functions, the programmer can designate that the new class should
22

inherit the members of an existing class. This existing class is called the base
class, and the new class is referred to as the derived class. Base & Derived
Classes: A class can be derived from more than one class or interface, which
means that it can inherit data and functions from multiple base classes or
interfaces.
The concept of inheritance is a common feature of an object-oriented
programming language. Inheritance allows a programmer to define a general
class, and then later define more specific classes that share or inherit all of the
properties of the more general class. This allows the programmer to save time
and energy that might otherwise be spent writing duplicate code. Related to
inheritance is the concept of polymorphism. Polymorphism allows us to define
different methods with the same name, but have those methods do different
things with different objects. This is related to method overloading, but as we will
see is different in that the position of the object in the inheritance hierarchy
determines what method gets invoked.
Visual studio.net namespaces.
All namespaces in your project are based on the root namespace for the
project. Visual Studio assigns your project name as the default root
namespace for all code in your project. For example, if your project is
named ConsoleApplication1 , its programming elements belong to the
namespace ConsoleApplication1.
Namespaces organize the objects defined in an assembly. Assemblies can contain
multiple namespaces, which can in turn contain other namespaces. Namespaces
prevent ambiguity and simplify references when using large groups of objects such as
class libraries.
For example, the .NET Framework defines the ListBox class in the
System.Windows.Forms namespace. The following code fragment shows how to
declare a variable using the fully qualified name for this class:
Dim LBox As System.Windows.Forms.ListBox
Avoiding Name Collisions
.NET Framework namespaces address a problem sometimes called namespace
pollution, in which the developer of a class library is hampered by the use of similar
names in another library. These conflicts with existing components are sometimes
called name collisions.
For example, if you create a new class named ListBox, you can use it inside your
project without qualification. However, if you want to use the .NET Framework ListBox
class in the same project, you must use a fully qualified reference to make the reference
unique. If the reference is not unique, Visual Basic produces an error stating that the
name is ambiguous. The following code example demonstrates how to declare these
objects:
' Define a new object based on your ListBox class.
Dim LBC As New ListBox
' Define a new Windows.Forms ListBox control.
23

Dim MyLB As New System.Windows.Forms.ListBox


The following illustration shows two namespace hierarchies, both containing
an object named ListBox:

By default, every executable file you create with Visual Basic contains a
namespace with the same name as your project. For example, if you define an
object within a project named ListBoxProject, the executable file
ListBoxProject.exe contains a namespace called ListBoxProject.
Multiple assemblies can use the same namespace. Visual Basic treats them as a
single set of names. For example, you can define classes for a namespace called
SomeNameSpace in an assembly named Assemb1, and define additional classes for
the same namespace from an assembly named Assemb2.
Fully Qualified Names
Fully qualified names are object references that are prefixed with the name of the
namespace in which the object is defined. You can use objects defined in other
projects if you create a reference to the class (by choosing Add Reference from
the Project menu) and then use the fully qualified name for the object in your
code. The following code fragment shows how to use the fully qualified name for
an object from another project's namespace.
Fully qualified names prevent naming conflicts because they make it possible for
the compiler to determine which object is being used. However, the names
themselves can get long and cumbersome. To get around this, you can use the
Imports statement to define an alias—an abbreviated name you can use in place
of a fully qualified name. For example, the following code example creates aliases
for two fully qualified names, and uses these aliases to define two objects.
Imports LBControl = System.Windows.Forms.ListBox
Imports MyListBox = ListBoxProject.Form1.ListBox
If you use the Imports statement without an alias, you can use all the names in that
namespace without qualification, provided they are unique to the project. If your project
contains Imports statements for namespaces that contain items with the same name,
you must fully qualify that name when you use it.
Namespace Level Statements
Within a namespace, you can define items such as modules, interfaces, classes,
delegates, enumerations, structures, and other namespaces. You cannot define items
such as properties, procedures, variables and events at the namespace level. These
items must be declared within containers such as modules, structures, or classes.
Global Keyword in Fully Qualified Names
If you have defined a nested hierarchy of namespaces, code inside that hierarchy might
be blocked from accessing the System namespace of the .NET Framework. The
following example illustrates a hierarchy in which the SpecialSpace.System namespace
blocks access to System.
24

Namespace SpecialSpace
Namespace System
Class abc
Function getValue() As System.Int32
Dim n As System.Int32
Return n
End Function
End Class
End Namespace
End Namespace
25

UNIT II
Windows Designing a Form using Forms Designer Window
The Windows Forms Designer provides many tools for building Windows Forms
applications. This article illustrates how to build an app by using the various tools
provided by the designer, including the following tasks:
● Arrange controls by using snaplines.
● Accomplish designer tasks by using smart tags.
● Set margins and padding for controls.
● Arrange controls by using a TableLayoutPanel control.
● Partition your control’s layout by using a SplitContainer control.
● Navigate your layout with the Document Outline window.
● Position controls with the size and location information display.
● Set property values by using the Properties window.
When you're finished, you'll have a custom control that's been assembled by using
many of the layout features available in the Windows Forms Designer. This control
implements the user interface (UI) for a simple calculator. The following image shows
the general layout of the calculator control:

Create the custom control project


The first step is to create the DemoCalculator control project.
1. Open Visual Studio and create a new Windows Forms Control Library
project by using the .NET Framework template for either C# or Visual Basic.
Name the project DemoCalculatorLib.
2. To rename the file, in Solution Explorer, right-click UserControl1.vb or
UserControl1.cs, select Rename, and change the file name to
DemoCalculator.vb or DemoCalculator.cs. Select Yes when you're asked if you
want to rename all references to the code element "UserControl1".
The Windows Forms Designer shows the designer surface for the DemoCalculator
control. In this view, you can graphically design the appearance of the control by
selecting controls and components from Toolbox and placing them on the designer
surface. For more information about custom controls, see Varieties of custom controls.
Design the control layout
The DemoCalculator control contains several Windows Forms controls. In this
procedure, you'll arrange the controls by using the Windows Forms Designer.
26

1. In the Windows Forms Designer, change the DemoCalculator control to


a larger size by selecting the sizing handle in the lower-right corner and
dragging it down and to the right. In the lower-right corner of Visual Studio,
find the size and location information for controls. Set the size of the control
to width 500 and height 400 by watching the size information as you resize
the control.
2. In the Toolbox, select the Containers node to open it. Select the
SplitContainer control and drag it onto the designer surface.
3.
4. In the Properties window, change the value of the Dock property to None.
The SplitContainer control shrinks to its default size and no longer follows the
size of the DemoCalculator control.
5. Select the smart tag glyph ( ) on the upper-right corner of the SplitContainer
control. Select Dock in the Parent Container to set the Dock property to Fill.
6. Select the vertical border between the panels and drag it to the right, so that the
left panel takes most of the space.
The SplitContainer divides the DemoCalculator control into two panels with a
movable border separating them. The panel on the left holds the calculator
buttons and display, and the panel on the right shows a record of the arithmetic
operations performed by the user.
7. In the Properties window, change the value of the BorderStyle property to
Fixed3D.
8. In Toolbox, select the Common Controls node to open it. Select the ListView
control and drag it into the right panel of the SplitContainer control.
9. Select the ListView control's smart tag glyph. In the smart tag panel, change the
View setting to Details.
10. In the smart tag panel, select Edit Columns.
The ColumnHeader Collection Editor dialog box opens.
11. In the ColumnHeader Collection Editor dialog box, select Add to add a column to
the ListView control. Change the value of the column's Text property to History.
Select OK to create the column.
12. In the smart tag panel, select Dock in Parent Container, and then select the
smart tag glyph to close the smart tag panel.
13. From the Containers node Toolbox, drag a TableLayoutPanel control into the left
panel of the SplitContainer control.
The TableLayoutPanel control appears on the designer surface with its smart tag
panel open. The TableLayoutPanel control arranges its child controls in a grid.
The TableLayoutPanel control holds the DemoCalculator control's display and
buttons. For more information, see Walkthrough: Arrange controls by using a
TableLayoutPanel.
14. Select Edit Rows and Columns on the smart tag panel.
The Column and Row Styles dialog box opens.
15. Select the Add button until five columns are displayed. Select all five columns,
and then select Percent in the Size Type box. Set the Percent value to 20. This
action sets each column to the same width.
16. Under Show, select Rows.
27

17. Select Add until five rows are displayed. Select all five rows, and the select
Percent in the Size Type box. Set the Percent value to 20. This action sets
each row to the same height.
18. Select OK to accept your changes, and then select the smart tag glyph to close
the smart tag panel.
19. In the Properties window, change the value of the Dock property to Fill.
Populate the control
Now that the layout of the control is set up, you can populate the DemoCalculator
control with buttons and a display.
1. In the Toolbox, select the TextBox control icon.
A TextBox control is placed in the first cell of the TableLayoutPanel control.
2. In the Properties window, change the value of the TextBox control's
ColumnSpan property to 5.
The TextBox control moves to a position that is centered in its row.
3. Change the value of the TextBox control's Anchor property to Left, Right.
The TextBox control expands horizontally to span all five columns.
4. Change the value of the TextBox control's TextAlign property to Right.
5. In the Properties window, expand the Font property node. Set Size to 14,
and set Bold to true for the TextBox control.
6. Select the TableLayoutPanel control.
7. In the Toolbox, select the Button icon.
A Button control is placed in the next open cell of the TableLayoutPanel
control.
8. In Toolbox, select the Button icon four more times to populate the second
row of the TableLayoutPanel control.
9. Select all five Button controls by selecting them while holding down the
Shift key. Press Ctrl+C to copy the Button controls to the clipboard.
10. Press Ctrl+V three times to paste copies of the Button controls into the
remaining rows of the TableLayoutPanel control.
11. Select all 20 Button controls by selecting them while holding down the Shift
key.
12. In the Properties window, change the value of the Dock property to Fill.
All the Button controls dock to fill their containing cells.
13. In the Properties window, expand the Margin property node. Set the value of
All to 5.
All the Button controls are sized smaller to create a larger margin between
them.
14. Select button10 and button20, and then press Delete to remove them from
the layout.
15. Select button5 and button15, and then change the value of their RowSpan
property to 2. These buttons represent the Clear and = buttons for the
DemoCalculator control.
Use the Document Outline window
When your control or form is populated with several controls, you may find it easier to
navigate your layout with the Document Outline window.
28

1. On the menu bar, choose View > Other Windows > Document Outline.
The Document Outline window shows a tree view of the DemoCalculator
control and its constituent controls. Container controls like the
SplitContainer show their child controls as subnodes in the tree. You can
also rename controls in place by using the Document Outline window.
2. In the Document Outline window, right-click button1, and then select
Rename. Change its name to sevenButton.
Implement event handlers
The buttons on the DemoCalculator control have event handlers that can be used to
implement much of the calculator logic. The Windows Forms Designer enables you to
implement the stubs of all the event handlers for all the buttons with one selection.
1. On the designer surface, select all the Button controls by selecting them
while holding down the Shift key.
2. Select one of the Button controls.
The Code Editor opens to the event handlers generated by the designer.
Test the control
Because the DemoCalculator control inherits from the UserControl class, you can test
its behavior with the UserControl Test Container. For more information, see How to: Test
the run-time behavior of a UserControl.
1. Press F5 to build and run the DemoCalculator control in the UserControl
TestContainer.
2. Select the border between the SplitContainer panels and drag it left and
right. The TableLayoutPanel and all its child controls resize themselves to fit
in the available space.
3. When you're finished testing the control, select Close.
Use the control on a form
The DemoCalculator control can be used in other composite controls or on a form. The
following procedure describes how to use it.
Create the project
The first step is to create the application project. You'll use this project to build the
application that shows your custom control.
1. Create a new Windows Forms Application project and name it
DemoCalculatorTest.
2. In Solution Explorer, right-click the DemoCalculatorTest project, and then
select Add > Project Reference to open the Reference Manager dialog box.
3. Go to the Projects tab, and then select the DemoCalculatorLib project to
add the reference to the test project.
4. In Solution Explorer, right-click DemoCalculatorTest, and then select Set as
StartUp Project.
5. In the Windows Forms Designer, increase the size of the form to about 700
x 500.
Use the control in the form's layout
To use the DemoCalculator control in an application, you need to place it on a form.
1. In Toolbox, expand the DemoCalculatorLib Components node.
29

2. Drag the DemoCalculator control from Toolbox onto your form. Move the
control to the upper-left corner of the form. When the control is close to
the form's borders, snap lines appear. Snap Lines indicate the distance of
the form's Padding property and the control's Margin property. Position the
control at the location indicated by the snaplines.
Drag a Button control from Toolbox and drop it onto the form.
3. Move the Button control around the DemoCalculator control and observe
where the snaplines appear. You can align your controls precisely and
easily by using this feature. Delete the Button control when you're finished.
4. Right-click the DemoCalculator control, and then select Properties.
5. Change the value of the Dock property to Fill.
6. Select the form, and then expand the Padding property node. Change the
value of All to 20.
The size of the DemoCalculator control is reduced to accommodate the
new Padding value of the form.
7. Resize the form by dragging the various sizing handles to different
positions. Observe how the DemoCalculator control is resized to fit.

Exploring the Forms Designer generated code


As you create a new project in Visual Basic, the IDE generally automatically adds lots of lines of
code on its own. Visual Basic 2005 comes with an option to skip over this behavior of the Visual
Basic IDE. The default option comes with this behavior enabled.
These codes are introduced with an aim that the user can continue to use the form without
bothering about writing codes to instantiate the form with a function new() and also the code
includes the declaration and instantiation of all the controls that have been dragged and
dropped onto the form. As a developer you may need to add controls like text boxes, grid
controls, database controls and also need to bind data to some control at design time.
Much of these activities can be done at design time and visually without adding any line of
code. The Visual Basic IDE is equipped with an inbuilt facility that generates codes for these
features. The more interesting part is not just that. You can actually add functionality to the form
by adding codes to these functions like new() which is the first function to be executed and can
be used to perform additional tasks at the start time of the application or even before the form
load takes place.
The .NET Framework provides superior security features in the application by introducing new
features. The code access security allows you to permit varied degrees or trust to the code
depending on where the code originates and also other factors that define the identity of the
code. Security permissions are implemented to ensure security. Code can request the
permissions it needs.
30

InitializeComponent: This method helps to persist the property values that you have set in
the Designer.The .NET Framework security system determines whether such requests are
honored. Requests are honored after verifying the code’s evidence and only relevant requests
are granted those permissions. The permission given to the code never exceeds the current
security settings. However, code will be granted less permission based upon a request.

The identity of the code forms the basis for granting the runtime permissions, also the level of
trust the code is granted is determined by the security policy.Code can demand that its callers
have specific permissions. If you place a demand for certain permission on your code, all code
that uses your code must have that permission to run.
There are three kinds of permissions, each with a specific purpose
● Code access permissions, which represent access to a protected resource or the ability
to perform a protected operation.
● Identity permissions, which indicate that code has credentials that support a particular
kind of identity.
● Role-based security permissions, which provide a mechanism for discovering whether a
user has a particular identity or is a member of a specified role. Thus a very robust and
well managed security is provided in the .NET Framework.
In Visual Basic .NET 2005
Discover some of the new features in Visual Basic.NET 2005 such as partial classes, generics,
operator overloading and using block
New features in Visual Basic.NET 2005
build on platform’s power and efficiency
Although Microsoft.NET languages have more or less the same facilities and power, one must
be aware of the syntax and capabilities of a language to take full advantage of it. This article
introduces new features of the upcoming Visual Basic.NET language that is part of Visual
Studio.NET 2005.
Visual Basic is one of the most popular languages used in the software development industry.
Its popularity comes from simplicity and efficiency. The new version of Visual Basic.NET builds
upon these attributes and introduces the following useful new features:
● my namespace
● partial classes
● generics
● operator overloading
● using block
My namespace
The My namespace feature includes functions and properties to do a lot of complex things in a
rapid manner. Think of this as shortcut syntax to get things done with less code. It groups
commonly required information and functionalities for easier access. The examples below show
how My namespace retrieves the current culture of the application compared to VB.NET 2003:
VB.NET 2003 Code:
stem.Threading.Thread.CurrentThread.CurrentCulture
VB.NET 2005 Code:
.Application.CurrentCulture
Even actions such as accessing various properties of the computer can be done easily and
quickly with My namespace. The following code, for example, will return a boolean indicating
the availability of the network:
.Computer.Network.IsAvailable
Partial classes
31

Partial classes define a class in multiple files. This separation is useful when you want to
have functionality of a class coded with different concerns and using inheritance might not
be appropriate.
Partial classes are used in Visual Studio.NET 2005 for auto-generated code. When you create a
windows form, for example, the Visual Studio.NET 2005 IDE creates a lot of auto-generated
code. In previous versions, this code is wrapped in regions in the same source file as
event-handling code. In Visual Studio.NET 2005, auto-generated code is separated from
event-handling code by defining it in a separate source file as a partial class. Here’s an example
of how a partial class can be defined:
rtial Public Class PersonPrivate pName As StringPrivate pAge As IntegerEnd Class
The above definition defines a class with the keyword “Partial” indicating that the definition of
the class is split into multiple source files.
rtial Public Class PersonPublic Property Name() As StringGetReturn Me.pNameEnd
tSet(ByVal value As String)Me.pName = valueEnd SetEnd PropertyPublic Property Age() As
egerGetReturn Me.pAgeEnd GetSet(ByVal value As Integer)Me.pAge = valueEnd SetEnd
opertyEnd Class
Now we are providing more definition of our Person class in a separate source file, providing
properties to expose our private fields.
Partial class can also be used to make your datasets more intelligent. The typed datasets you
create in Visual Studio.NET have the partial class definition for the generated source. This
enables you to add value to your typed dataset by providing functionality such as business logic
by defining a partial class definition for the generated class.
Generics
Generics enable your program to adapt itself to different types. The concept of generics is used
in the implementation of collections in the new framework. Let’s define a simple customer class
as follows:
Public Class CustomerPrivate name As StringSub New(ByVal value As String)Me.name =
ueEnd SubEnd Class
If we want to manipulate a collection of customer objects, a typical implementation in VB.NET
2003 would be:
Dim col As New Collections.ArrayListcol.Add(New Customer("John"))col.Add(New
stomer("Smith"))col.Add("A String")
The problem with this implementation is even though you wanted your collection to only handle
customers, there is no way of enforcing this. To restrict your collection to handle only
customers, you will need to implement a custom collection class by extending the facilities
provided by the collection framework. But what if you want to implement different collections to
handle different types of objects? You might end up with a lot of custom collections to handle
different types of objects even though the functionality you require from these collections is the
same.
32

This is where generics come in. They give you a way to implement a placeholder for the type
and then specify what the type is. An ideal solution to the previous problem would be to
provide the implementation of the collection with the type of the collection as a variable; when
creating a collection we would specify what the collection should manipulate. That’s exactly the
functionality of the collections provided by the System.Collections.Generic namespace in Visual
Basic.NET 2005:If you try to add a string or anything other than customer objects, the compiler
will detect it as a syntax error. You can also define your own generic functionality to program to
types that are not known in advance or to enable your program to work with multiple types.The
above class is defined by using the variable “T” as a placeholder. When you create an instance
of GenericClass you replace the placeholder type with a real type. Once we do this, our Accept
method will accept only arguments of the real type defined while instantiating GenericClass. For
example:Operator overloading

dim strGeneric As GenericClass(Of Customer)strGeneric.Accept(New Customer("John"))

Operator overloading enables you to specify what operators such as + or – should do when
invoked with objects of classes you define. For example :
Dim val As New Boxval.Area = value1.Area + value2.Areaval.Weight = value1.Weight +
ue2.WeightReturn val

The above class definition is a simple box with an area and weight as properties. We wanted to
provide functionality to add two box objects and return a box with the area and weight as the
total of added boxes. We have overloaded the meaning of the + operator to work with Box
objects by defining how it should work. We could have defined a new method with a name to
achieve this, but using operators for similar operations makes the code more readable and easy
to use. To add two box objects, we simply use the + operator in a way similar to adding two
numbers:
m b As Box = New Box(12, 32) + New Box(15, 19)
Using block
Some objects you create are very resource intensive. So a good practice is to release the
resource as soon as you are finished with it. Generally when you create an object inside a
method, the object will not be released until the method terminates. But what if you want an
easy way to define an object as well as specify the scope of it inside a method? The using block
helps you to achieve this:
Using con As New System.Data.SqlClient.SqlConnection'Other statements using conEnd
ng
In the above code, the scope of the defined con object will be limited within the using block and
will be released as soon as it exits that block.
Rich and rapid
Visual Basic.NET is one of the popular languages in the .NET platform and future versions are
making it richer without losing the rapid development approach for which it’s renowned. This
article should help users take immediate advantage of new features that will be an integral part
of Visual Studio.NET 2005 and the Microsoft.NET 2.0 platform.
33

Message Class

VB.NET, here are some additional explanations and notes:

Encapsulation:

The Message class uses encapsulation to bundle the properties (Sender, Recipient, Subject,
Body) together.
The properties are declared as Public to allow access from outside the class. You can choose to
make them private and provide public methods to access or modify them if you want stricter
encapsulation.
Constructors:

The class has two constructors: a default constructor with no parameters and a parameterized
constructor that allows you to initialize the properties during object creation.
Constructors are used to set initial values for the properties of the class.
Initialization:

The properties can be set individually after creating an instance of the class or during the object
creation using the constructor.
Usage:

You can create instances of the Message class and set their properties to represent different
messages.
The provided example in the Module1 demonstrates creating instances of the Message class,
setting their properties, and displaying the message details.
Methods (if needed):

You can add methods to the Message class if you need specific functionality associated with
messages. For example, you might want to add a method to send the message or perform
some validation on the message content.
Access Modifiers:

In this example, properties are declared as Public. Depending on your needs, you might want to
use different access modifiers like Private, Protected, or Friend to control the visibility of
properties outside the class.
Default Values:

The default constructor doesn't set any default values for the properties. You may modify it to
set default values if needed.
ToString Method (Optional):

You might consider overriding the ToString method in the Message class to provide a
human-readable representation of the message. This can be useful for debugging or logging
purposes.
Remember that this is a basic example, and as your application grows, you might need to
enhance the Message class based on your specific requirements and best practices.
34

Public Class Message


' Properties
Public Property Sender As String
Public Property Recipient As String
Public Property Subject As String
Public Property Body As String

' Constructors
Public Sub New()
' Default constructor
End Sub

Public Sub New(sender As String, recipient As String, subject As String, body As String)
' Parameterized constructor
Me.Sender = sender
Me.Recipient = recipient
Me.Subject = subject
Me.Body = body
End Sub

' Methods (if needed)


' You can add methods here to perform specific actions related to the message.

End Class

Application Class
In VB.NET, an application class is typically a class that serves as the entry point for your
application. It is where you define the application's main method, which is executed
when the application starts. The application class contains the Main method, and it can
be used to set up the application, handle command-line arguments, and initiate the
application's main functionality.

The Application object provides a diverse range of functionality, including support for
multithreaded programming, access to the system registry, and support for subclassing
(intercepting messages sent to application windows). It also includes a variety of
informational functions, such as properties to retrieve the company name, to retrieve
the application’s executable path, and to retrieve the application’s name and version.

Application objects can be created as follows:

Dim obj As Application


35

However, because all of the Application object’s members are shared, you do not
need to instantiate the Application object to access its properties and methods.
Hence, you can retrieve the executable path of your application, for instance, with the
code fragment:

Dim sPath As String = Application.ExecutablePath

Application class members marked with a plus sign (+) are discussed in detail in their
own entries.

Public Properties

AllowQuit

CommonAppDataPath

CommonAppDataRegistry

CompanyName +

CurrentCulture

CurrentInputLanguage

ExecutablePath +

LocalUserAppDataPath

MessageLoop

ProductName +

ProductVersion +

SafeTopLevelCaptionFormat

StartupPath

UserAppDataPath
36

UserAppDataRegistry

Public Shared Methods

AddMessageFilter

DoEvents +

Exit

ExitThread

OleRequired

OnThreadException

RemoveMessageFilter

Run

Public Shared Events

ApplicationExit

Idle

ThreadException

ThreadExit

Imports System.Collections.Generic

Public Class Note


Public Property Title As String
Public Property Content As String
Public Property CreatedDate As DateTime

Public Sub New(title As String, content As String)


Me.Title = title
Me.Content = content
CreatedDate = DateTime.Now
End Sub

Public Overrides Function ToString() As String


Return $"Title: {Title}, Content: {Content}, Created Date: {CreatedDate}"
37

End Function
End Class

Public Class NotesManager


Private NotesList As List(Of Note)

Public Sub New()


NotesList = New List(Of Note)()
End Sub

Public Sub AddNote(title As String, content As String)


Dim newNote As New Note(title, content)
NotesList.Add(newNote)
End Sub

Public Function GetNotes() As List(Of Note)


Return NotesList
End Function

Public Function GetNoteByTitle(title As String) As Note


Return NotesList.FirstOrDefault(Function(n) n.Title = title)
End Function

Public Sub UpdateNote(title As String, newContent As String)


Dim noteToUpdate As Note = GetNoteByTitle(title)
If noteToUpdate IsNot Nothing Then
noteToUpdate.Content = newContent
End If
End Sub

Public Sub DeleteNoteByTitle(title As String)


Dim noteToDelete As Note = GetNoteByTitle(title)
If noteToDelete IsNot Nothing Then
NotesList.Remove(noteToDelete)
End If
End Sub
End Class
38

UNIT III
Building graphical interface elements
Graphics handling in Visual Basic .NET is based on GDI+ (Graphics Device Interface). A graphics
device interface allows you to display graphics on a screen or a printer without having to handle
the details of a specific display device. All that you need to do is to make calls to methods
supported by the GDI+ classes and those methods make the corresponding calls to individual
device drivers as needed to handle the screen or printer.
To create a graphics object
Receive a reference to a graphics object as part of the System.Windows.Forms.PaintEventArgs
in the System.Windows.Forms.Control.Paint event of a form or control. This is usually how you
obtain a reference to a graphics object when creating painting code for a control.
Call the System.Windows.Forms.Control.CreateGraphics method of a control or form to obtain a
reference to a System.Drawing.Graphics object that represents the drawing surface of that
control or form. Use this method if you want to draw on a form or control that already exists.
Create a System.Drawing.Graphics object from any object that inherits from
System.Drawing.Image. This approach is useful when you want to alter an already existing
image.

Understanding The Windows Forms Coordinate System


GDI+ uses three coordinate spaces: world, page, and device. World coordinates are the
coordinates used to model a particular graphic world and are the coordinates you pass to
methods in the .NET Framework. Page coordinates refer to the coordinate system used by a
drawing surface, such as a form or control. Device coordinates are the coordinates used by the
physical device being drawn on, such as a screen or sheet of paper.
When you make the call myGraphics.DrawLine(myPen, 0, 0, 160, 80), the points that you pass to
the System.Drawing.Graphics.DrawLine method—(0, 0) and (160, 80)—are in the world
coordinate space. Before GDI+ can draw the line on the screen, the coordinates pass through a
sequence of transformations. One transformation, called the world transformation, converts
world coordinates to page coordinates, and another transformation, called the page
transformation, converts page coordinates to device coordinates.
Transforms and Coordinate Systems
39

Suppose you want to work with a coordinate system that has its origin in the body of the
client area rather than the upper-left corner. Say, for example, that you want the origin to be
100 pixels from the left edge of the client area and 50 pixels from the top of the client area. The
following illustration shows such a coordinate system.

When you make the call myGraphics.DrawLine(myPen, 0, 0, 160, 80), you get the line shown in
the following illustration.

The coordinates of the endpoints of your line in the three coordinate spaces are as follows:

World
(0, 0) to (160, 80)

Page
(100, 50) to (260, 130)

Device
(100, 50) to (260, 130)

The code snippet to draw the line shown in the above picture is given below:

myGraphics.TranslateTransform(100, 50)

myGraphics.DrawLine(myPen, 0, 0, 160, 80)


.
.Drawing Text on a Form
40

Drawing text on a Form can be achieved by the following method. You can use the
System.Drawing.Graphics.Drawstring method of the System.Drawing.Graphics class to draw
text. This example will be using the System.Windows.Forms.PaintEventArgs e, which is a
parameter of System.Windows.Forms.PaintEventHandler. Let us see a demo for this task. In a
new project add the following codes:
You have to add a button and set the value for the text property to “Exit”.

The drawText method takes one parameter System.Windows.Forms.PaintEventArgs e. This


method is called from the System.Windows.Forms.PaintEventHandler method which causes the
Text to be drawn on the Form.

We declare a variable myText and assign it a value also. We also declare a fontFamily as an
object of type FontFamily Which sets the name for the font family. We also declare a font object
of the type Font and set values for its properties like FontFamily, Size, Style and Graphics Unit.
This defines the visual properties of the Font that we want to display. The DrawString method
which takes four parameters is used to draw Text. Here you can choose the type of brush by
declaring your own brush. The output is given below for the above project.

Adding Controls
Most forms are designed by adding controls to the surface of the form to define a user
interface (UI). A control is a component on a form used to display information or accept
user input.
The primary way a control is added to a form is through the Visual Studio Designer, but
you can also manage the controls on a form at run time through code.
Add with Designer
Visual Studio uses the Forms Designer to design forms. There is a Controls pane which
lists all the controls available to your app. You can add controls from the pane in two
ways:
Add the control by double-clicking
When a control is double-clicked, it is automatically added to the current open form with
default settings.
41

Add the control by drawing


Select the control by clicking on it. In your form, drag-select a region. The control will be
placed to fit the size of the region you selected.

Common Controls and Handling Control Events


42

we will be learning how to use common control like Control Hierarchy, Label and LinkLabel,
TextBox and RichTextBox, PictureBox, GroupBox and Panel, Button, CheckBox and
RadioButton, ListBox, CheckedListBox and ComboBox, DomainUpDown and NumericUpDown,
MonthCalendar and DateTimePicker, TreeView and ListView, Timer, TrackBar and ProgressBar,
HScrollBar, VScrollBar, TabControl and Handling Control Events.All controls are governed by the
Control Class “System.Windows.Forms” Namespace. This class handles the entire basic
window handle (HWND) functionality such as the creation and destruction of window handles.
When Control and Rich Control are integrated VB.NET provides for greater functionality.A
number of properties are shared by all controls in a class. Any change in such shared properties
impacts on all controls in the class. Some of the shared properties are listed below.
DefaultBackColor: Read-only. Returns what the background color of the control would be if the
background color were set explicitly

DefaultFont: Read-only. Returns what the font of the control would be if the font were set
explicitly

DefaultForeColor: Read-only. Returns what the foreground color of the control would be if the
foreground color is changed.
Public Shared Properties
Public shared properties are distinct from properties that are shared by controls
of a class in that the value of the property is not shared across the controls in a
class. Any change in the property of a control does not result in a change in the
properties of the controls in the class. Even when two instances of an object are
created, each can have a distinct value assigned to a property. Examples of
public instance properties are listed below for your understanding.

AccessibilityObject Specified the AccessibleObject assigned to the control.

BackColor Specifies the background color

Cursor Specifies the cursor that is displayed when the mouse pointer
moves over the control

Focused Read-only. Returns whether the control is currently as the input


focus.

Size Specifies the size of the control

Anchor Specifies which edges of the control are bound to the edges of its
container

Dock Specifies to which edge of the container the control is docked.


When specified, the resizing of the control is handled automatically.
Controls that are “dockable” require code analyzing window
movements coupled with the setting of this property
43

Font Specifies the current font of the control

Location Specifies the coordinates of the upper-left corner of the control


relative to the upper-left corner of the controls container

Name Specifies the name of the control. This value is typically used to
refer to the control in code

Size Specifies the height and width of the full control

TabIndex Specifies this control’s place in the tab order for all controls within
the same container

TabStop Specifies whether the control can receive focus via the tab key

Visible Specifies whether the control is visible

Enabled Specifies whether the control is enabled. This also covers items
such as receiving focus

Configuring the order of tabs


A user is required to move across a form in a prescribed order. The tab order of the
control determines the way in which the cursor moves in the form and takes the user
through the various options created for his use. This is a very important property for the
application designer as it determines the sequence of user input if any.Click on the
control in the form and edit the TabIndex property and change its value. The value for
this property is given in integers. This will be enabled only if the TabStop Property is set
to true. Let us see an example for this feature.
1. Create a new project in the visual Studio IDE and add a form.
2. Drag and add 18 Command Buttons to this form and arrange them in a matrix.
3. Pick any 6 of them and select them.
4. Set the property enabled to false.
5. This can also be done at runtime as shown in the example.
6. Position two buttons separately as shown in the form.
7. You can also add two labels one at the top and the other at the bottom.
8. For each of the remaining Buttons do the following changes:
1. From the first button on the top left change their name in order and
give them a new name (First, Second … Tenth)
2. You will find that the TabIndex value would have already been set as
per the order of their placement in the form.
3. Change their values so that the label named first will have the value 1
and the label that has the name Tenth will have a value 10.
4. At the bottom of the form you will have one label control and two
command buttons. Set the name value for the label as null and that
of the first command button to “Reverse Order!”. Let the name of the
second command button be “Exit”. Now your form will look like the
screenshot given below.
44

Execute the project by pressing F5. This example illustrates the purpose of the properties and
also the method used to assign the properties at run time. Please note that the property
TabStop is not available to all properties. For example the controls like Label and LinkLabel do
not expose this property.
Handling Control Events
Controls are used as a primary medium of handling events. Rich sets of events are specified for
controls and their nature can be easily understood by reading their names. For example OnClick,
MouseEnter, MouseLeave etc. describe the nature of the event they handle. Some of the events
and their descriptions are given below:
Event Name Description

BackColorChanged Occurs when the BackColor property of the control is changed

BindingContextChanged Occurs when the BindingContext property of the control


changes

ChangeUICues Occurs when focus or keyboard cues changes

ContextMenuChanged Occurs when the Contextmenu Property of the control is


changed
45

KeyUp Occurs when a key is released while the control has focus

Move Occurs when the control is moved

Resize Occurs when the control is resized

Paint Occurs when the control is drawn or redrawn

LocationChanged Occurs when the location property of the control changes

Validating Occurs when the visible property of the control changes


All controls have been declared with the functionalities built into them and therefore are capable
of executing the function when the user calls the event. This process is enabled by using the
term “Handles”. The program that is executed will look like the one below.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click

————

————

End Sub
The event handler takes two parameters in the above instance. The first is the sender as
System.Object and the other is the valued ‘e’ as System.EventArgs. The Sender defines the
object that has raised the event and the EventArg contains all the event specific data that the
event sender passes.
There are other types of arguments that are accepted, such as FileSystemEventArgs,
ImageClickEventArgs, KeyEventArgs and CommandEventArgs. Using the SenderObject could be
particularly useful if any action from out of a set of grouped actions is to be performed. Let us
look at an example of this.
Start a new Visual Basic Windows Application Project in the Visual Studio IDE.
Add seven buttons and four labels and rename the buttons as shown as shown in the following
screenshot.
46

Here, we have used a CommonHandler that does some action based on the output of the
various events. This is a simple code that changes the text of the labels. You can also write
complex codes using loops that perform some action based on the event of the object that has
sent the event. This facility is very useful in solving complex problems with simple solutions
quickly.

Dialog Boxes in Visual Basic .NET 2005


Most Windows applications request for user input. Dialog boxes are one means of requesting users for
specific kinds of inputs. Therefore, VB.NET allows its designers to create a number of different types of
dialog boxes. Standard Dialog boxes are included in classes that fall within the purview of the
CommonDialog.
1. FileDialog
2. ColorDialog
3. FontDialog
4. PageSetupDialot
5. PrintDialog
Let us now briefly study the features of the CommonDialog boxes
OpenFileDialogClass
This class provides users with the file selection capability. The properties and methods of this dialog boxes
are given below:
perty or Method cription

wDialog plays the dialog

tiSelect s/unsets the selection of multiple files

wReadOnly s/unsets the read-only check box checked


47
er s the type of files that will appear in the dialog box

erIndex s the index of the filter selected in the dialog box

SaveFileDialog Class
The SaveFileDialog class offers you the standard window that we see while saving the file. The methods and
properties of this dialog box are given below:
perty or Method cription

wDialog plays the message

ckFileExists cks for the existence of file specified

Name ermines the file name selected by the user

er dition for files to be shown in the dialog box

erIndex ermine the index of the filter selected in the dialog box

The ColorDialog Class


This dialog box shows the color palette for allowing the user to select a color and add that color to the
palette. The properties of the Class are given below:
perty or Method cription

wDialog plays the dialog box

or ermines the color selected by the user

wFullOpen cifies if the user can add custom colors to the box

dColorOnly ermines if the user can use dithered colors

The following screenshot shows the usage of the color palette:


Create a new Visual Basic Windows Applications project in the Visual Studio IDE . To the form Form1 add a
ColorDialogBox. Add two Buttons and name them as given below:
48

Now in the code behind form add the following codes:


Public Class Form1

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


System.EventArgs) Handles Button1.Click

Me.ColorDialog1.ShowDialog()

Label1.ForeColor = Me.ColorDialog1.Color

End Sub

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


System.EventArgs) Handles Button2.Click

Me.Close()

End Sub

End Class
Press F5 to execute the program
49
The three screenshots below illustrate how different common dialog boxes are displayed..

“Change Color” button opens the ColorDialog box. You can choose any color from the palette and click Ok.
(The codes for event handling of Ok and Cancel button in the ColorDialogBox are not given in this program.
You may however write it as shown earlier, if you want to see the impact of your program.) The next
screenshot will show the changed fore color of the label1:

Creating a Custom Dialog Box


■ In a new project which already has a form Form1, add another form and name it as FixeDialog.
■ Set the Text property of this form as “Add Text”.
■ Add a label control, a text box control and two command buttons.
■ Change the text property of the label to “Enter Your Text!” and name the first button OK and
the other as Cancel.
■ In the property sheet of the form set the FormBorderStyle property to FixedDialog
■ Set the ControlBox property as false. This is done to remove minimize, maximize and close
buttons.
■ Enter the following codes for the Dialog Form:
Click here for the Sample Code
Now press F5 to execute the program. The Following sequence of three screenshot will illustrate the
working of the form:
The first screenshot shows the initial screen of the program:

The following screenshot shows the custom dialog box opened with the new text typed in the text box:
50
51

Common Windows Forms Controls Section

Windows Forms offers controls and components that perform a number of functions.
The following table lists the Windows Forms controls and components according to
general function. In addition, where multiple controls exist that serve the same function,
the recommended control is listed with a note regarding the control it superseded. In a
separate subsequent table, the superseded controls are listed with their recommended
replacements.

Function Control Description

Data DataGridView control The DataGridView control provides a


display customizable table for displaying data. The
DataGridView class enables customization of
cells, rows, columns, and borders. Note: The
DataGridView control provides numerous
basic and advanced features that are missing
in the DataGrid control. For more information,
see Differences Between the Windows
Forms DataGridView and DataGrid Controls

Data BindingSource Simplifies binding controls on a form to data


binding and component by providing currency management, change
navigation notification, and other services.

BindingNavigator control Provides a toolbar-type interface to navigate


and manipulate data on a form.

Text editing TextBox control Displays text entered at design time that can
be edited by users at run time, or changed
programmatically.

RichTextBox control Enables text to be displayed with formatting


in plain text or rich-text format (RTF).
52

MaskedTextBox control Constrains the format of user input

Information Label control Displays text that users cannot directly edit.
display
(read-only)

LinkLabel control Displays text as a Web-style link and triggers


an event when the user clicks the special
text. Usually the text is a link to another
window or a Web site.

StatusStrip control Displays information about the application's


current state using a framed area, usually at
the bottom of a parent form.

ProgressBar control Displays the current progress of an operation


to the user.

Web page WebBrowser control Enables the user to navigate Web pages
display inside your form.

Selection CheckedListBox control Displays a scrollable list of items, each


from a list accompanied by a check box.

ComboBox control Displays a drop-down list of items.

DomainUpDown control Displays a list of text items that users can


scroll through with up and down buttons.

ListBox control Displays a list of text and graphical items


(icons).
53

ListView control Displays items in one of four different views.


Views include text only, text with small icons,
text with large icons, and a details view.

NumericUpDown control Displays a list of numerals that users can


scroll through with up and down buttons.

TreeView control Displays a hierarchical collection of node


objects that can consist of text with optional
check boxes or icons.

Graphics PictureBox control Displays graphical files, such as bitmaps and


display icons, in a frame.

Graphics ImageList control Serves as a repository for images. ImageList


storage controls and the images they contain can be
reused from one application to the next.

Value CheckBox control Displays a checkbox and a label for text.


setting Generally used to set options.

CheckedListBox control Displays a scrollable list of items, each


accompanied by a check box.

RadioButton control Displays a button that can be turned on or


off.

TrackBar control Allows users to set values on a scale by


moving a "thumb" along a scale.

Date DateTimePicker control Displays a graphical calendar to allow users


setting to select a date or a time.

MonthCalendar control Displays a graphical calendar to allow users


to select a range of dates.
54

Dialog ColorDialog control Displays the color picker dialog box that
boxes allows users to set the color of an interface
element.

FontDialog control Displays a dialog box that allows users to set


a font and its attributes.

OpenFileDialog control Displays a dialog box that allows users to


navigate to and select a file.

PrintDialog control Displays a dialog box that allows users to


select a printer and set its attributes.

PrintPreviewDialog Displays a dialog box that displays how a


control control PrintDocument component will appear
when printed.

FolderBrowserDialog Displays a dialog that allows users to browse,


control create, and eventually select a folder

SaveFileDialog control Displays a dialog box that allows users to


save a file.

Menu MenuStrip control Creates custom menus. Note: The MenuStrip


controls is designed to replace the MainMenu control.

ContextMenuStrip Creates custom context menus. Note: The


control ContextMenuStrip is designed to replace the
ContextMenu control.

Commands Button control Starts, stops, or interrupts a process.


55

LinkLabel control Displays text as a Web-style link and triggers


an event when the user clicks the special
text. Usually the text is a link to another
window or a Web site.

NotifyIcon control Displays an icon in the status notification


area of the taskbar that represents an
application running in the background.

ToolStrip control Creates toolbars that can have a Microsoft


Windows XP, Microsoft Office, Microsoft
Internet Explorer, or custom look and feel,
with or without themes, and with support for
overflow and run-time item reordering. Note:
The ToolStrip control is designed to replace
the ToolBar control.

User Help HelpProvider component Provides pop-up or online Help for controls.

ToolTip component Provides a pop-up window that displays a


brief description of a control's purpose when
the user rests the pointer on the control.

Grouping Panel control Groups a set of controls on an unlabeled,


other scrollable frame.
controls

GroupBox control Groups a set of controls (such as radio


buttons) on a labeled, non scrollable frame.

TabControl control Provides a tabbed page for organizing and


accessing grouped objects efficiently.
56

SplitContainer control Provides two panels separated by a movable


bar. Note: The SplitContainer control is
designed to replace the Splitter control.

TableLayoutPanel Represents a panel that dynamically lays out


control its contents in a grid composed of rows and
columns.

FlowLayoutPanel control Represents a panel that dynamically lays out


its contents horizontally or vertically.

Audio SoundPlayer control Plays sound files in the .wav format. Sounds
can be loaded or played asynchronously.

Superseded Controls and Components by Function

Function Superseded Recommended


control replacement

Data display DataGrid DataGridView

Information Display (Read-only StatusBar StatusStrip


controls)

Menu controls ContextMenu ContextMenuStrip

MainMenu MenuStrip

Commands ToolBar ToolStrip

StatusBar StatusStrip

Form layout Splitter SplitContainer


57

DomainUpDown and NumericUpDown

A visual basic NumericUpDown control is said to be a pair of a TextBox Control and the Up
Down arrows. The NumericUpDown Control generally works as a counter in which a user can
input a numeric value. It is also called a Spin box. The arrow in the NumericUpDown Control
works to increase or decrease the value. Up arrow is for increasing the value and the down
arrow is for decreasing the value. If you hold the mouse on the up arrow it will increase the value
till the maximum value in the list and then stop. Its reverse condition works with the down arrow;
the Specific range is also defined for the values. The example for the NumericUpDown Control is
the Volume control in any Music Player.

The below example shows the use of NumericUpDown control:-

● Create a new Project


● Add a NumericUpDown control, a Label and a Button. The form will look like below.
58
● Add the below code to the form.

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs)Handles
Button1.Click
Me.Close()
End Sub
Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, ByVal eAs
System.EventArgs)
Handles NumericUpDown1.ValueChanged
Label1.Text = "The current Value of the counter is : " & NumericUpDown1.Value
End Sub
End Class

Output:-

DomainUpDown Control:-

DomainUpDown control is used to allow users to move up or down to a particular value.


It shows a textbox and an up and down arrow that allows the user to move between its
values. TheDomainUpDown control Shows and sets a text string from a given list of
choices. If you want to select a string you can do this by pressing the up and down
button and also by typing the string in the TextBox that matches the string in the list.

The below example shows the use of DomainUpDown control:-

● Create a new project.


59
● Add TextBox, CheckBox and two Buttons then form will look like below.
60
● Add the Below code to the form.

Protected WithEvents domainUpDown As DomainUpDown


Private myCounter As Integer = 1
Private Sub MySub()
domainUpDown = New System.Windows.Forms.DomainUpDown()
Controls.Add(domainUpDown)
End Sub
Private Sub button1_Click(ByVal sender As System.Object, ByVal e AsSystem.EventArgs)
Handles
Button1.Click
domainUpDown.Items.Add((TextBox1.Text.Trim() & " - " & myCounter))
myCounter = myCounter + 1
TextBox1.Text = ""
End Sub
Private Sub checkBox1_Click(ByVal sender As System.Object, ByVal e AsSystem.EventArgs)
Handles
CheckBox1.CheckedChanged
If domainUpDown.Sorted Then
domainUpDown.Sorted = False
Else
domainUpDown.Sorted = True
End If
End Sub
Private Sub domainUpDown_SelectedItemChanged_(ByVal sender As
System.Object,ByVal e As
System.EventArgs)
MessageBox.Show(("SelectedIndex: " & domainUpDown.SelectedIndex.ToString() & _
ControlChars.Cr & "SelectedItem: " & domainUpDown.SelectedItem.ToString()))
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e AsSystem.EventArgs)
Handles
MyBase.Load
MySub()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e AsSystem.EventArgs)
Handles
Button2.Click
Me.Close()
End Sub

Output:-
61
62

Creating Menu and Menu Items


A menu is used as a menu bar in the Windows form that contains a list of related commands,
and it is implemented through MenuStrip Control. The Menu control is also known as the
VB.NET MenuStrip Control. The menu items are created with ToolStripMenuItem Objects.
Furthermore, the ToolStripDropDownMenu and ToolStripMenuItem objects enable full control
over the structure, appearance, functionalities to create menu items, submenus, and drop-down
menus in a VB.NET application.

Let's create a MenuBar by dragging a MenuStrip control from the toolbox and dropping it to the
Windows form.

Step 1. Drag the MenuStrip control from the toolbox and drop it on to the Form.

Step 2: Once the MenuStrip is added to the form, we can set various properties of the
Menu by clicking on the MenuStrip control.

Properties of the MenuStrip Control

There are following properties of the VB.NET MenuStrip control.

Properties Description

CanOverflow The CanOverflow property is used to authenticate whether the

control supports overflow functionality by setting values in the

MenuStrip control.
63

Stretch The Stretch property is used to obtain a value that specifies

whether the menustrip stretches from end to end in the MenuStrip

control.

GripStyle The GripStyle property obtains or sets the visibility of the grip that

uses the reposition of the menu strip control.

ShowItemToolTi It is used to obtain or set the value that determines if the ToolTips

ps are displayed for the MenuStrip Control.

DefaultSize The DefaultSize property is used to get the default horizontal and

vertical dimension of the MenuStrip in pixel when it is first created.

Methods of the MenuStrip Control

Method Description

CreateAccessibilityInsta It is used to create a new accessibility instance for the

nce() MenuStrip Control.

ProcessCmdKey() The ProcessCmdKey method is used to process the

command key in the MenuStrip Control.

CreateDefaultItem() The CreateDefaultItem method is used to create a

ToolStripMenuItem with the specified text, image, and

event handlers for the new MenuStrip.

OnMenuActivate() It is used to initiate the MenuActivate event in the

MenuStrip control.
64

OnMenuDeactivate() It is used to start the MenuDeactivate event in the

MenuStrip control.

Events of the MenuStrip Control

Events Description

MenuActivate When a user uses a menu bar control with a mouse or keyboard, a

MenuActivate event occurs.

MenuDeactiva The MenuDeactivate event occurs when the MenuStrip control is

te deactivated in the Windows form.

Let's create a program to display the menu bar in the Windows form.

In this image, we have created the menu and sub-items of the menu bar in the form.

Now, we write the Shortcut keys for the File subitems, such as New -> Ctrl + N, Open ->
Ctrl + O, etc.
65

After that, we can see the subitems of the Files with their Shortcut keys, as shown
below.

Menus.vb
66

1. Public Class Menus


2. Private Sub Menus_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
3. Me.Text = "javatpoint.com" 'set the title of the bar
4. BackColor = Color.SkyBlue
5. End Sub
6.
7. Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs)
Handles ExitToolStripMenuItem.Click
8. Me.Dispose() ' exit from the form
9. End Sub
10. End Class

Output:

Click on the File menu that shows the multiple options related to files.
67

Creating Multiple-Document Interface (MDI)


MDI stands for Multiple Document Interface applications that allow users to work with multiple
documents by opening more than one document at a time. Whereas, a Single Document
Interface (SDI) application can manipulate only one document at a time.

The MDI applications act as the parent and child relationship in a form. A parent form is a
container that contains child forms, while child forms can be multiple to display different
modules in a parent form.

VB.NET has following rules for creating a form as an MDI form.

1. MidParent: The MidParent property is used to set a parent form to a child form.

2. ActiveMdiChild: The ActiveMdiChild property is used to get the reference of the current
child form.

3. IsMdiContainer: The IsMdiContainer property sets a Boolean value to True that


represents the creation of a form as an MDI form.

4. LayoutMdi(): The LayoutMdi() method is used to arrange the child forms in the parent or
main form.

5. Controls: It is used to get the reference of control from the child form.
68

Let's create a program to display the multiple windows in the VB.NET Windows Forms.

Backward Skip 10s


Play Video
Forward Skip 10s

Step 1: First, we have to open the Windows form and create the Menu bar with the use of
MenuStrip control, as shown below.

Step 2: After creating the Menu, add the Subitems into the Menu bar, as shown below.
69

In the above image, we have defined two Subitems, First is the Feedback Form, and the
Second is VB.NET.

Step 3: In the third step, we will create two Forms: The Child Form of the Main Form or Parent
Form.

Here, we have created the first Child Form with the name Form2.

Form2.vb

1. Public Class Form2


2. Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
3. Me.Text = "Feedback form" ' Set the title of the form
4. Label1.Text = " Fill the Feedback form"
5. Button1.Text = "Submit"
6. Button1.BackColor = Color.SkyBlue
7. Button2.Text = "Cancel"
8. Button2.BackColor = Color.Red
9. End Sub
10. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
11. MsgBox(" Successfully submit the feedback form")
12. End Sub
13. Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
14. Me.Dispose() ' end the form2
15. End Sub
16. End Class

Another Child Form with the name Form3.

Form3.vb

1. Public Class Form3


2. Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
3. Label1.Text = "Welcome to JavaTpoint Tutorial Site"
4. Label.BackColor = Color.Green
5. Label2.Text = "This is the VB.NET Tutorial and we are learning the VB.NET MDI
Form"
70

6. Label2.BackColor = Color.SkyBlue
7. End Sub
8. End Class

Step 4: Now we write the programming code for the Main or Parent Form, and here is the code
for our Main Form.

MDI_form.vb

1. Public Class MDI_Form


2. Private Sub MDI_Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
3. IsMdiContainer = True 'Set the Boolean value to true to create the form as an MDI
form.
4. Me.Text = "javatpoint.com" 'set the title of the form
5. PictureBox1.Image = Image.FromFile("C:\Users\AMIT YADAV\Desktop\jtp2.png")
6. PictureBox1.Height = 550
7. PictureBox1.Width = 750
8. End Sub
9. Private Sub FeedbackFormToolStripMenuItem_Click(sender As Object, e As
EventArgs) Handles FeedbackFormToolStripMenuItem.Click
10. PictureBox1.Visible = False
11. Dim fm2 As New Form2
12. fm2.MdiParent = Me 'define the parent of form3, where Me represents the same
form
13. fm2.Show() 'Display the form3
14. End Sub
15. Private Sub VBNETToolStripMenuItem_Click(sender As Object, e As EventArgs)
Handles VBNETToolStripMenuItem.Click
16. PictureBox1.Visible = False
17. Dim fm3 As New Form3
18. fm3.MdiParent = Me 'define the parent of form3, where Me represent the same form
19. fm3.Show() 'Display the form3
20. End Sub
71

21. End Class

Output:

After that, click on the Menu button, it shows two sub-items of the Menu as Feedback Form and
VB.NET. We have clicked on the Feedback Form that displays the following form on the window.
72

When we click on the Menu item, it shows the following image on the screen.
73

Applications Validation
Validating user input can be quite a pain, especially if you do not know what techniques and
what namespaces are at your disposal. Because everyone has a different way of doing things,
my methods might not be 100% the same as your methods. This is why I decided to make use
of Regular Expressions here within this article. Today you will learn how to use regular
Expressions to validate user input.

In simple terms, validation refers to ensuring entered data is well valid. Determining whether or
not data is valid can sometimes be a painstaking process as there are numerous tests that need
to be thought of. These tests include:

1. Format test – This test determines if the entered string is in the correct format.
2. Type test – This test checks if the input is the correct type. For example: Integers of
dates that do not need conversion afterwards.
74

3. Permitted Character test – This test ensures that no illegal characters are
entered. For example: If a user is supposed to enter a name, numbers and some
special symbols must not be allowed.
4. Range test – This tests checks to see if entered values are within a specified range.
For example : If you are only supposed to type in 50 characters, you must not be able
to enter more than fifty.

There are two types of validation:

1. Form-level Validation - Validates all fields on a form simultaneously.


2. Field-level validation - Validates each field as data is entered.

Define field-level validation and form-level validation.

Field-level validation means validating each field as it receives focus. Form-level validation is the
process where you validate all data on a form before the form is submitted.

Exceptions
An exception is a problem that arises during the execution of a program. An
exception is a response to an exceptional circumstance that arises while a program
is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another.
VB.Net exception handling is built upon four keywords - Try, Catch, Finally and
Throw.

​ Try − A Try block identifies a block of code for which particular exceptions will
be activated. It's followed by one or more Catch blocks.
​ Catch − A program catches an exception with an exception handler at the
place in a program where you want to handle the problem. The Catch
keyword indicates the catching of an exception.
​ Finally − The Finally block is used to execute a given set of statements,
whether an exception is thrown or not thrown. For example, if you open a
file, it must be closed whether an exception is raised or not.
​ Throw − A program throws an exception when a problem shows up. This is
done using a Throw keyword.

Syntax

Assuming a block will raise an exception, a method catches an exception using a


combination of the Try and Catch keywords. A Try/Catch block is placed around the
code that might generate an exception. Code within a Try/Catch block is referred to
as protected code, and the syntax for using Try/Catch looks like the following −

Try
75

[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try

You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception in different situations.

Exception Classes in .Net Framework

In the .Net Framework, exceptions are represented by classes. The exception


classes in .Net Framework are mainly directly or indirectly derived from the
System.Exception class. Some of the exception classes derived from the
System.Exception class are the System.ApplicationException and
System.SystemException classes.

The System.ApplicationException class supports exceptions generated by


application programs. So the exceptions defined by the programmers should derive
from this class.

The System.SystemException class is the base class for all predefined system
exception.

The following table provides some of the predefined exception classes derived from
the Sytem.SystemException class −

Exception Class Description

System.IO.IOException Handles I/O errors.

System.IndexOutOfRangeException Handles errors generated when a


method refers to an array index
out of range.

System.ArrayTypeMismatchException Handles errors generated when


type is mismatched with the
array type.

System.NullReferenceException Handles errors generated from


deferencing a null object.
76

System.DivideByZeroException Handles errors generated from


dividing a dividend with zero.

System.InvalidCastException Handles errors generated during


typecasting.

System.OutOfMemoryException Handles errors generated from


insufficient free memory.

System.StackOverflowException Handles errors generated from


stack overflow.

Handling Exceptions

VB.Net provides a structured solution to the exception handling problems in the


form of try and catch blocks. Using these blocks the core program statements are
separated from the error-handling statements.

These error handling blocks are implemented using the Try, Catch and Finally
keywords. Following is an example of throwing an exception when dividing by zero
condition occurs −

Live Demo
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −

Exception caught: System.DivideByZeroException: Attempted to divide by zero.


at ...
Result: 0
77

Creating User-Defined Exceptions

You can also define your own exception. User-defined exception classes are derived
from the ApplicationException class. The following example demonstrates this −

Live Demo
Module exceptionProg
Public Class TempIsZeroException : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Public Class Temperature
Dim temperature As Integer = 0
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If
End Sub
End Class
Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −

TempIsZeroException: Zero Temperature found

Throwing Objects

You can throw an object if it is either directly or indirectly derived from the
System.Exception class.

You can use a throw statement in the catch block to throw the present object as −

Throw [ expression ]
78

The following program demonstrates this −

Module exceptionProg
Sub Main()
Try
Throw New ApplicationException("A custom exception _ is
being thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −

A custom exception is being thrown here...


Now inside the Finally Block
79

UNIT IV
Creating and Managing Components Section
A component is a class that implements the System.ComponentModel.IComponent interface or
that derives directly or indirectly from a class that implements IComponent. A .NET component
is an object that is reusable, can interact with other objects, and provides control over external
resources and design-time support.

An important feature of components is that they are designable, which means that a class that
is a component can be used in the Visual Studio Integrated Development Environment. A
component can be added to the Toolbox, dragged and dropped onto a form, and manipulated on
a design surface. Base design-time support for components is built into .NET. A component
developer does not have to do any additional work to take advantage of the base design-time
functionality.

A control is similar to a component, as both are designable. However, a control provides a user
interface, while a component does not. A control must derive from one of the base control
classes: Control or Control.

When to Create a Component

If your class will be used on a design surface (such as the Windows Forms or Web Forms
Designer) but has no user interface, it should be a component and implement IComponent, or
derive from a class that directly or indirectly implements IComponent.

The Component and MarshalByValueComponent classes are base implementations of the


IComponent interface. The main difference between these classes is that the Component class
is marshaled by reference, while IComponent is marshaled by value. The following list provides
broad guidelines for implementers.

● If your component needs to be marshaled by reference, derive from Component.


● If your component needs to be marshaled by value, derive from
MarshalByValueComponent.
● If your component cannot derive from one of the base implementations due to
single inheritance, implement IComponent.

Component Classes

The System.ComponentModel namespace provides classes that are used to implement the
run-time and design-time behavior of components and controls. This namespace includes the
base classes and interfaces for implementing attributes and type converters, binding to data
sources, and licensing components.

The core component classes are:

● Component. A base implementation for the IComponent interface. This class


enables object sharing between applications.
80

● MarshalByValueComponent. A base implementation for the IComponent


interface.
● Container. The base implementation for the IContainer interface. This class
encapsulates zero or more components.

Some of the classes used for component licensing are:

● License. The abstract base class for all licenses. A license is granted to a specific
instance of a component.
● LicenseManager. Provides properties and methods to add a license to a
component and to manage a LicenseProvider.
● LicenseProvider. The abstract base class for implementing a license provider.
● LicenseProviderAttribute. Specifies the LicenseProvider class to use with a class.

Classes commonly used for describing and persisting components.

● TypeDescriptor. Provides information about the characteristics for a component,


such as its attributes, properties, and events.
● EventDescriptor. Provides information about an event.
● PropertyDescriptor. Provides information about a property.

Creating Components by extending the UserControl Class, Testing the Control, Creating and
implementing Events, Extending a control through Visual Inheritance and Inheriting from a
UserControl.

A component is a reusable piece of code in binary form. This code can be reused by inheritance. No
class is being inherited. It follows that a containment relationship is defined between the application
using the component and the component that is being used. This is different from the relationship
that exists between a derived class and a base class.

Components have to interact with each other. They need information about each other. This is
achieved by loading the components within self-contained packages called assembly. An assembly
contains information about the files on which the component depends and the location of these
files. The CLR can use this information to determine the dependencies of a component. The
assemblies that are required during the execution of an application are called dependencies.

A class becomes a component when it follows defined standards of interaction. These standards
are provided by the IComponent interface. All components derive from Component class. The
Component class in turn implements IComponent interface.

Best practices in using components

■ The name of the component to be short and meaningful.


■ The access level for constructors should be implemented as private or public based
on the usage is either by the same assembly or different assembly.
■ The base class of all components is Component class. You can also implement an
IComponent interface to create a component.
81
■ The namespace structure in an assembly should be according to the internal
organization of the component. It is preferable to keep all the components
together in a separate Namespace.
■ The component will have two types of initialization namely, type initialization and
instance initialization.
■ Type initialization is achieved by using a shared constructor and this is done only once
in the lifetime of the application.
■ Instance initialization is achieved by using the constructors which are not shared.
■ A component like any other class must implement as many interfaces as needed.
They are capable of being called in multiple ways.(polymorphism).

Creating components by extending the UserControl Class


Objects help users control the flow of applications. Objects like buttons and ComboBoxes are
controls. Controls can be defined as visual components that are used across applications. Controls
that are customized by users are called UserControls. User Controls can have multiple child controls
and provide the user with a single interface.

Let us now create a user control.

Open the Visual Studio IDE and select the menu File, Choose New – Project to open a new project
Dialog Box

Choose Windows Control Library from the items displayed. Type the name of the project as
InterestCalculator. Click on OK.

In the solution Explorer window, right-click UserControl1 and select View Code
82
You can also change the default name UserControl1 to any name of your choice

The class inherits from the UserControl class by default. If you need to inherit from another existing
control, edit the statement Inherits System.Windows.Forms.UserControl to refer to your class.

Save the project.

Enter the following code into the windows.

Click here for Sample Code

Testing the Control


The control is always used in a container. Therefore you need a windows form to test the control.
The Steps for doing this are as follows.

Build the control by clicking the Build menu.

Create a new windows application project

In the solution explorer window of the new project, right –click the Reference node. Select Add
reference to open the Add reference dialog box.

Add the project with your custom control to the selected Components section in the AddReference
DialogBox. To close the Add Reference dialog box.

Add the control to you toolbar

In the dialog box that you have opened select the .NET Framework Component tab from the Add
Reference Dialog Box.
83

Choose the ToolBox Item

.Creating and Managing .NET Assemblies


The .NET assembly is the standard for components developed with Microsoft.NET. Dot NET
assemblies may or may not be executable, i.e., they might exist as the executable (.exe) file or
dynamic link library (DLL) file. All the .NET assemblies contain the definition of types, versioning
information for the type, meta-data, and manifest. The designers of .NET have worked a lot on
the component (assembly) resolution.
84

An assembly can be a single file or it may consist of multiple files. In the case of multi-file,
there is one master module containing the manifest while other assemblies exist as
non-manifest modules. A module in .NET is a subpart of a multi-file .NET assembly. Assembly is
one of the most interesting and extremely useful areas of .NET architecture along with
reflections and attributes.

.NET supports three kinds of assemblies:


1. private
2. shared
3. satellite
Private Assembly

Private assembly requires us to copy separately in all application folders where we want to use
that assembly’s functionalities; without copying, we cannot access the private assembly
features and power. Private assembly means every time we have one, we exclusively copy into
the BIN folder of each application folder.

Public Assembly

Public assembly is not required to copy separately into all application folders. Public assembly
is also called Shared Assembly. Only one copy is required at the system level, there is no need to
copy the assembly into the application folder.

Public assembly should be installed in GAC.

Shared assemblies (also called strong named assemblies) are copied to a single location
(usually the Global assembly cache). For all calling assemblies within the same application, the
same copy of the shared assembly is used from its original location. Hence, shared assemblies
are not copied in the private folders of each calling assembly. Each shared assembly has a
four-part name including its face name, version, public key token, and culture information. The
public key token and version information makes it almost impossible for two different
assemblies with the same name or for two similar assemblies with a different version to mix
with each other.

GAC (Global Assembly Cache)

When the assembly is required for more than one project or application, we need to make the
assembly with a strong name and keep it in GAC or in the Assembly folder by installing the
assembly with the GACUtil command.

Satellite Assembly

Satellite assemblies are used for deploying language and culture-specific resources for an
application.
85

Assemblies are the core building blocks of .NET applications. In simple terms, assembly is
the .dll or .exe file that is created while building any .NET application. You can find many
definitions for assembly over the internet also. In my point of view, assembly is the building
block that is created after a successful build operation of your application.

After the compilation of each project, a .exe or .dll file is generated, known as Assembly. The
name of an assembly file is the same as the project name. The assembly of a project present
under the bin\Debug folder of that project folder. After the successful build of each project, an
assembly is generated inside that folder. We can use assembly files by our requirement. We may
directly take the assembly file and install it into the client machine if it is .exe type or we can
consume the file in another project if the assembly is dll type.

Class Library and Windows Forms Control Library projects generate a .dll assembly whereas
Windows Forms Applications, Console Applications, WPF Applications, and Windows Services
projects generate a .exe assembly.

.Exe type assembly is run by their own as well as they provide support to others in their
execution process so these assemblies are known as an in-process component whereas .dll
type assembly is called as out process component because they are only developed for the
purpose to consume inside .exe type of application.

Types of Assembly:

In .NET, we have two types of assemblies:


1. Private Assembly
2. Shared Assembly
Private Assembly

When we build any project we find a corresponding assembly inside the bin/Debug folder; so by
default, this assembly is a private type. It's private because when we add that assembly
reference to another project then a copy of that assembly is created inside that project. Below
figure is an example of Private assembly.
86

Creating an assembly to test if it is private, by default:

Start a new project inside Visual studio of type Class Library and name it as “PAssembly”,we
take the class library because we can consume this project dll file inside another project. Here I
am using VS2012 for my project creation.
in this project, you find a file called Class1.cs. Now, write the following code under the class:

● public string TestHello() {


● return "Hello from private assembly";
● }

Now, compile the project by opening the Solution Explorer, right-clicking on the project, and
selecting “Build” or Press "Ctrl+shift+B" which will build + compile your project and generate an
assembly with the name PAssembly.dll.

Testing the assembly we have created

Open a new project of type Windows, name it as “TestPAssembly”, place a button on the Form,
and set its text as “Call TestHello method of Class1 in PAssembly.dll”. Now, add the reference of
PAssembly.dll from its physical location and write the following code under the click of a button:
87

● PAssembly.Class1 obj = new PAssembly.Class1();


● MessageBox.Show(obj. TestHello ());

Run the project to test it. Then, go and verify under the bin/debug folder of the current project
where we can find a copy of PAssembly.dll as it is a private assembly.

Note: The advantage of a private assembly is faster execution because it is available in the local
folder, whereas its drawback is that multiple copies get created when multiple projects add the
reference to consuming it.

Shared Assemblies

As we saw above while consuming a private assembly it always created a copy of that file inside
the project bin/debug folder; so if we want to use that assembly in several applications then we
are required to put that assembly inside a shared folder. That shared folder in .Net is called a
Global Assembly Cache folder. We can add a number of assemblies inside that folder and
consume that assembly for any project.

Simple Data Binding-Complex Data Binding


The .NET framework supports simple and complex DataBinding. Simple data
binding is supported by controls like TextBoxes. In Simple databinding, only one
data value can be displayed by the control at a time. In complex databinding, which
is supported by controls like the DataGrid, more than one data value from the
DataSource can be displayed.
88

Dataflow during DataBinding

A good understanding of the dataflow from the control to the datasource is very
important. The diagram below gives an overview of the dataflow and the objects
involved.

In .NET, controls can have many properties that can be bound to a DataSource.
Each databound property has an associated Binding object. Since a control can
have many Binding objects, the control has a collection (instance of
ControlBindingsCollection class) of all the Binding objects. Also remember that
different properties of the same control can be bound to different datasource's.
89

Each Binding object talks to a CurrencyManager or a PropertyManager.


CurrencyManager and PropertyManager classes merit a little explanation, as they
are important. CurrencyManager and PropertyManager are derived from the base
class BindingManagerBase. The purpose of BindingManagerBase class is to
maintain the concurrency between the datasource and the control. Of the two
classes, the CurrencyManager is used when the datasource implements the IList
Interface. Examples of such data sources are DataView, DataSet, ArrayList etc.
The CurrencyManager can be used for simple as well as complex databinding.
However, the PropertyManager is used when the datasource is an instance of a
user-defined class. The Control's property is bound to the property exposed by this
object. PropertyManager can only be used for simple data binding.

As a rule of thumb if you want your class to be a datasource, you should use
CurrencyManager when your class is a data container. However, if you are
interested in binding a control to properties exposed by your own class, then using
a PropertyManager is easier, since you do not have to implement the IList
Interface.

Since a form can contain many controls each binding to a different datasource, a
class is needed to manage the CurrencyManager and PropertyManager objects.
Therefore, each windows form in .NET has a default BindingContext object
associated with it. But, you can always create more BindingContext objects on the
form. The BindingContext object is a collection of CurrencyManager and
PropertyManager objects.
90

Using the Data Form Wizard


The Data Form Wizard is a graphical tool for binding form controls to data sources. You can
create data-bound controls for Windows and Web applications with the Data Form Wizard. This
section examines the use of the wizard with Windows forms. If you are an Access developer
learning Visual Basic .NET and ADO.NET, one of the great advantages of using the Data Form
Wizard is that you can build form solutions for your Access databases without writing any code.
However, the code behind the automatically generated forms is all standard code. Therefore, you
can view the code as a learning aid or as a starting point for more customized solutions.

Menu for the Section


You will frequently build switchboard forms toward the end of an application development
project. This is because you need to have the forms to which a switchboard directs traffic
available for the code behind the switchboard form to compile properly. In spite of this
application development requirement, switchboard forms are useful in tutorial presentations at
the beginning of a section, such as this presentation. A switchboard form can succinctly
summarize the topics a section covers.

The form exists as Form1 in the DataFormWizSamples project. The code behind this form works
identically to the code behind the switchboard form in the preceding section, except that this
form's code references four samples instead of five. The most significant point of the samples
referenced from this switchboard is that the Data Form Wizard generated all their forms. I did
not have to code any of them. However, these forms do typical database chores in a database
form. The first sample enables data access and manipulation via text boxes. The second
sample enables data manipulation via a DataGrid control. The third sample presents two
DataGrid controls in a main/subform configuration. The fourth sample takes this main/subform
to a higher level by showing aggregated data in the sub form.

VB developers scoff at the concept of bound controls, they are very useful for quickly building a
prototype or proof-of-concept. In addition, bound controls work well to demonstrate some of the
functionality in VB.NET.

To start the DataForm Wizard, right-click the LearningVBData project node, select Add, and then
Add New Item. Double-click the DataForm Wizard icon. This starts the DataForm Wizard. The
first screen is just information, so after reading it, click the Next button.

Step 2 of the DataForm Wizard asks you to choose whether to use a new DataSet or to use one
you've already created. Because you have already created the DataSet you will be using, select
the Existing radio button. If you drop down the list, you should see only one DataSet, which is the
one you just finished creating: dsProducts. The DataSet is listed as LearningVBdata.dsProducts,
and the list of available tables is shown in the list box on the right side. Figure 6.8 shows what
your form should look like. Click the Next button after choosing your DataSet.

Step 3 of the wizard asks you what method you want to use to load the data store. Earlier, when
you added the controls and set the SQL statement, a FillDataSet method was created in
Component1. Choose the FillDataSet method for the first box.
91

Step 2 of the DataForm Wizard.

If you want, you can check the Include Update Method box, but be aware that doing so enables
you to manipulate the data as you work with it, and this might not be something you want to do.
However, if this is just a test machine, feel free to check this box and then select
UpdateDataSource as the method to use to update the data store. Figure 6.9 shows what this
screen should look like when you are done. Click Next to move forward.

Step 3 of the DataForm Wizard.


Step 4 of the DataForm Wizard displays a list of the tables in your DataSet, as well as the
columns in each table. If you had a DataSet with relationships between tables, you could even
display a hierarchical relationship with this screen. Make sure that all the fields are chosen and
click the Next button.

Finally, Step 5 asks whether you want to display all the records (which will show them in a grid)
or just a single record (which will show the record in text boxes).

If you choose the grid display, the generated form displays the DataSet in a Datagrid. A Datagrid
has the functionality to navigate, add, and remove records already built into it. Thus, choosing to
view the records in a grid removes the options for adding navigation controls, as well as buttons
for Add, Delete, and Cancel. Select the Single Record radio button and leave all the buttons
enabled, as shown in Figure 6.10. Click the Finish button to exit the wizard, have it create a form,
and work its magic.

Choosing how to view the data on the form.


The form sports a large number of controls: buttons, text boxes, and panels. Before running the
result, you need to set DataForm1 as the Startup object for your application. Select Properties
from the Project menu. In the Startup object drop-down, select Data Form and press the OK
button. Go ahead and run the form by clicking on the Start button.
92

After the form is loaded, click the Load button. This actually fills the DataSet and then
displays the first record on the form. Use the navigation buttons to walk through the records.
Figure 6.11 shows how your form should look.

Your first data-driven VB.NET form.


If you update the data, you will get an interesting lesson in just how ADO.NET works. For
example, in Figure 6.11, the current record is ProductID 9, Mishi Kobe Niku. The UnitsInStock is
29. If you change the UnitsInStock to 28, and then click the Next (>) button, you scroll to
ProductID 10. Then, if you click the Previous (<)

button, ProductID 9 shows a UnitsInStock of 28. "Aha!" you think. "I've updated that record." And
you have. But you haven't.

ADO.NET uses a disconnected paradigm. That means that the data in the DataSet is not
connected to the underlying database in real-time. The data you have changed is in the DataSet,
and not in the SQL Server table. You can verify this by opening SQL Server's Query Analyzer and
running the following SQL statement against the Northwind database:

Select * from Products where ProductID=9

This disconnected mode of working is why the DataForm Wizard adds an Update button. The
Update button calls the UpdateDataSource procedure that you selected in the DataForm Wizard.
As soon as you click the Update button, the data is updated in SQL Server. Using this
disconnected model, you could make multiple inserts, updates, and deletes, and then send them
to the underlying database all at once.

Some of you might have used disconnected recordsets in ADO. If so, this sounds familiar to you.
For those of you who didn't use ADO's disconnected recordsets, this might sound strange. Just
be aware that this is the default behavior in ADO.NET.

You can also see the data in the form of a grid. Select Add New Item from the Project menu.
Double-click the DataForm Wizard icon to start the DataForm Wizard. Choose the dsProducts
DataSet that you created earlier. In the method you want to use to load the data store, pick the
FillDataSet in Component1. Select the Products table and all the fields. Finally, choose to display
All Records (grid) on Step 5 of the wizard.

VB.NET adds a DataGrid control to the form, along with a Load button. Don't start the project yet;
if you do, you will see only Form1. To see DataForm2 at startup, right-click the project in the
Solution Explorer window and choose Properties. In the Startup Object box, choose
LearningVBdata.DataForm2. Now, start the project and click the Load button.
93

The ADO .NET Object Model-Access and Manipulate Data


Applications communicate with a database, firstly, to retrieve the data stored there
and present it in a user-friendly way, and secondly, to update the database by
inserting, modifying and deleting data.

Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net


framework that is used by the .Net applications for retrieving, accessing and
updating data.

ADO.Net Object Model


ADO.Net object model is nothing but the structured process flow through various
components. The object model can be pictorially described as −

The data residing in a data store or database is retrieved through the data
provider. Various components of the data provider retrieve data for the application
and update data.

An application accesses data either through a dataset or a data reader.

​ Datasets store data in a disconnected cache and the application retrieves


data from it.
​ Data readers provide data to the application in a read-only and
forward-only mode.
94

Data Provider
A data provider is used for connecting to a database, executing commands and
retrieving data, storing it in a dataset, reading the retrieved data and updating the
database.

The data provider in ADO.Net consists of the following four objects −

Sr.No. Objects & Description

1 Connection
This component is used to set up a connection with a
data source.

2 Command
A command is a SQL statement or a stored procedure
used to retrieve, insert, delete or modify data in a data
source.

3 DataReader
Data reader is used to retrieve data from a data source in
a read-only and forward-only mode.

4 DataAdapter
This is integral to the working of ADO.Net since data is
transferred to and from a database through a data
adapter. It retrieves data from a database into a dataset
and updates the database. When changes are made to
the dataset, the changes in the database are actually
done by the data adapter.

There are following different types of data providers included in ADO.Net

​ The .Net Framework data provider for SQL Server - provides access to
Microsoft SQL Server.
​ The .Net Framework data provider for OLE DB - provides access to data
sources exposed by using OLE DB.
​ The .Net Framework data provider for ODBC - provides access to data
sources exposed by ODBC.
​ The .Net Framework data provider for Oracle - provides access to Oracle data
source.
​ The EntityClient provider - enables accessing data through Entity Data Model
(EDM) applications.
95

DataSet
DataSet is an in-memory representation of data. It is a disconnected, cached set of
records that are retrieved from a database. When a connection is established with
the database, the data adapter creates a dataset and stores data in it. After the
data is retrieved and stored in a dataset, the connection with the database is
closed. This is called the 'disconnected architecture'. The dataset works as a virtual
database containing tables, rows, and columns.

The following diagram shows the dataset object model −

The DataSet class is present in the System.Data namespace. The following table
describes all the components of DataSet −

Sr.No. Components & Description

1 DataTableCollection
It contains all the tables retrieved from the data source.

2 DataRelationCollection
It contains relationships and the links between tables in a
data set.
96

3 ExtendedProperties
It contains additional information, like the SQL statement
for retrieving data, time of retrieval, etc.

4 DataTable
It represents a table in the DataTableCollection of a
dataset. It consists of the DataRow and DataColumn
objects. The DataTable objects are case-sensitive.

5 DataRelation
It represents a relationship in the
DataRelationshipCollection of the dataset. It is used to
relate two DataTable objects to each other through the
DataColumn objects.

6 DataRowCollection
It contains all the rows in a DataTable.

7 DataView
It represents a fixed customized view of a DataTable for
sorting, filtering, searching, editing and navigation.

8 PrimaryKey
It represents the column that uniquely identifies a row in
a DataTable.

9 DataRow
It represents a row in the DataTable. The DataRow object
and its properties and methods are used to retrieve,
evaluate, insert, delete, and update values in the
DataTable. The NewRow method is used to create a new
row and the Add method adds a row to the table.

10 DataColumnCollection
It represents all the columns in a DataTable.

11 DataColumn
It consists of the number of columns that comprise a
DataTable.

Connecting to a Database
The .Net Framework provides two types of Connection classes −

​ SqlConnection − designed for connecting to Microsoft SQL Server.


97

​ OleDbConnection − designed for connecting to a wide range of


databases, like Microsoft Access and Oracle.

Example
We have a table stored in Microsoft SQL Server, named Customers, in a database
named testDB. Please consult the 'SQL Server' tutorial for creating databases and
database tables in SQL Server.

Let us connect to this database. Take the following steps −

​ Select TOOLS → Connect to Database

​ Select a server name and the database name in the Add Connection dialog
box.
98

​ Click on the Test Connection button to check if the connection succeeded.


99

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

​ Choose DataSet as the database model.

​ Choose the connection already set up.


101

​ Save the connection string.

​ Choose the database object, Customers table in our example, and click the
Finish button.
102

​ 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 toolbar, it will show the following window −
103

XML Access Methods in .NET.

.NET offers numerous XML-related classes for reading and writing XML documents.
Although the documentation states that any class conforms to the W3C XML 1.0
standard, there are trade-offs in respect to performance, efficiency, productivity, and
XML compliance between the different implementations.
So we first investigated these different access methods and then selected the most
appropriate for our application. This step also addresses important issues that must be
considered when dealing with legacy valid and well-formed XML data in .NET.

The VB.NET developer can use any of the following five methods to access XML data:

● XmlTextReader
● XmlValidatingReader
● XmlDocument (and the rest of the DOM API),
● XPathNavigator.
● ADO.NET DataSets
104

The detailed description of these methods would go beyond the scope of this article.
Thus the following table summarizes very briefly the characteristics of each method and
shows when to use which technology.

XmlTextReader ● You need only read


access.
● Performance is your
highest priority.
● You don't need XSD/DTD
validation.
● You don't need XSD type
information at runtime.
● You don't need
XPath/XSLT services.

XmlValidatingRead ● You need only read


er access.
● You need XSD/DTD
validation.
● You need XSD type
information at runtime.

XmlDocument ● You need to update the


document (read/write).
● Productivity is your
highest priority.
● You need XPath
services.

XPathNavigator ● You need only read


access.
● You need to execute an
XSLT transformation.
● You want to leverage an
implementation (like
XPathDocument).

ADO.NET DataSets ● You need to update the


document (read/write).
● You need greatest
flexibility and
functionality.
● You want greatest tool
support.
● You need
interop-support.
105

Table 1. XML Data Access Methods in .NET.

When dealing with complex XML Schemas, then ADO.NET DataSet offers greatest
support and flexibility. The DataSet, which can be used either relational databases or
XML data files, is an in-memory cache of retrieved data. It is the major component for
data handling in the ADO.NET architecture.

The DataSet provides a consistent relational programming model regardless of the


data source; thus it consists of a collection of DataTable objects that you can relate to
each other with DataRelation objects. A DataSet reads and writes data and schema as
XML documents. The data and schema can be transported across HTTP and used by
any application, on any platform that is XML-enabled.

Considering all these features and the fact that this VB.NET application will need to be
WebService interoperable with a server application in future we decided to go for
DataSet's.

XML Conformance in .NET.

Going with DataSets, ReadXML and ReadXMLSchema are the methods of choice to
read the XML data, and the corresponding XML schema.

However doing so with the given valid and well-formed XML data file, raised the
following runtime error:

"The same table {description} cannot be the child table in two nested relations".

Looking deeper into the file shows that the valid and well-formed (and thus fully W3C
compliant) XML file had a child table called "description" which had more than one
parent table. This part of the XML Schema is shown in Figure 1 .
106

Figure 1. Original XML Schema.

This is a valid and allowed design according to the W3C XML schema specification.
(Refer: W3C definition of Parent child Relationship). Also the XMLSpy tool validated this
XML schema as valid and well-formed.

More investigation showed that the .NET XML framework does not (yet?) support the
full XML 1.0 standard. It does not support recursive schemas or designs where a child
node type is beneath more than one parent node type. Of course, also all classes based
on DataSets, like the System.Windows.Forms.DataGrid, which we were going to use,
have the same restriction. In other words:

XML Design Issue 1: ".NET Datasets require that a table can only be a child of one
other table."

Microsoft has identified this as a bug (Q325695) and their knowledge base article
[MS-Q325695] gives more information.
There are essentially three ways to solve this problem:

● Write custom functions


● Write a converter
107

● Change your XML Schema

If you can't change the existing XML Schema (for example because you are not the
owner of the file), there are two ways to solve the problem: you customize all your ode,
or you write a converter.

Customizing all your code means you write special methods for the XmlReader class
and add records to a table with a hierarchical type design. You also have to implement a
custom filtering mechanism if you want to display this data in bound controls, and a
custom writing mechanism to write to the type of hierarchical format you are reading
from. Even worse, any change in the schema file will cause changes in all of your

custom functions - so this isn't really an.

The second option, if you can't change the given XML Schema, is to write a converter.
That means you define a new .NET compliant XML Schema for the given XML file and
make use of the given DataSet capabilities. Then you write a bi-directional converter to
convert the data from one XML Schema into the other before you use it. Although this
still causes additional effort, it causes the least additional effort.

If you are the owner of the XML Schema file, then the solution is to change the given
XML Schema and make it also .NET compliant. In our situation, this meant, to define
three different description type structures (Idescription, Description, Description), for the
three occurrences of the description.

To avoid multiple definitions of the same structure (which can cause maintenance errors
in the future), we made use of the inheritance capabilities of XML Schema. We derived
the three description types from the still existing base structure "description". The details
are shown in figure 2.
108

Figure 2. Avoid one child with several parents.

Reading XML Data with DataSets.

VB.NET developers have several approaches to using a DataSet in the applications.


This section explains the chosen approach to create a DataSet from the modified XML
Schema, the tools that were used and how we populated the DataSet from the XML
source file.

A DataSet can be typed or untyped. A typed DataSet is a dataset, which is created


based on a given XML Schema definition file (XSD file). Information from the schema
(tables, columns, etc.) is generated and compiled into the new DataSet class as a set of
first-class objects and properties.

Because a typed DataSet class inherits from the base DataSet class, the typed class
assumes all of the functionality of the DataSet class and can be used with methods that
take an instance of a DataSet class as a parameter.

An untyped DataSet, in contrast, has no corresponding built-in schema. As in a typed


dataset, an untyped DataSet contains tables, columns - but those are exposed only as
collections. (However, after manually creating the tables and other data elements in an
untyped DataSet, you can export the DataSet's structure as a schema using the
DataSet 's WriteXmlSchema method.).
109

You can use either type of DataSet in your application. However, Visual Studio has
more tool support for typed DataSets, and they make programming with the DataSet
much easier and less error-prone. So having considered all these options the decision
was to go with ADO.NET typed DataSets.

Typed Datasets can be generated with the XSD.EXE tool, which is part of the VS.NET
environment. The tool accepts a valid XML Schema file as input, as well as the
language to use (C#, VB). The following line shows a typical command line of the tool
which uses the XML Schema file XSDSchemaFileName.xsd.

xsd.exe /d /l:VB.NET XSDSchemaFileName.xsd /n:XSDSchema.Namespace.

The /d directive tells the tool to generate DataSets, /l specifies the language to use, the
optional /n defines the namespace to generate. The generated DataSet classes will be
saved in the source file XSDSchemaFileName.vb.

Once the Typed DataSet classes are generated, the further procedure is almost a
child's play. The provided methods and properties guarantee data access in a type safe
manner.

So the next step was to populate the Typed DataSet at runtime from the XML file. The
ReadXml() and the WriteXml() methods of the typed DataSet class do this very easily
without any difficulty as the following to lines of code show:

Dim myDS As New DataSet.

myDS.ReadXml("input.xml", XmlReadMode.ReadSchema).

Viewing XML Data.


110

Having created and populated the DataSet the next step was to bind the data to the
windows controls for user interaction. Since we were going to implement a grid view,
this involved binding DataTables to DataGrids with user navigation facilities and
providing parent-child relationships in the grid view so when a user selects a parent row,
the corresponding child rows are to be shown automatically for editing purposes.

The DataTable is the primary building block of ADO.NET. The DataTable is made up of
DataColumn and DataRow collections. The columns define the schema of the
DataTable and the rows make up the actual data in the DataTable. A DataView is a
bindable, customized view of a DataTable. You can create multiple Data Views of the
same DataTable, each one can contain different data sorted in different order.
Additionally, you can add, delete, or edit information in each DataView.

DataTable and DataView use the same instances of DataColumns, i.e. they share the
common structure. However DataTable and DataView each have its own row
collections. The DataTable is consists of DataRow's while the DataView is made up
DataRowView. Figure 3 shows the relationship between DataSet, DataTable and
DataView.

Figure 3. Tables and Views.


111

The data binding of typed DataSets is very smooth in VB.NET. You can bind the data
sources to the WindowsForms controls at design time or runtime without any difficulty.
For example, you can specify which data column to be bound to a ComboBox in a
WindowsForm by setting the DataSource and DataMember property of that control so
that it gets automatically bound at runtime.

We used the .NET DataView class to bind DataTables to the DataGrid. DataView
supports data filtering and data sorting at design time or at runtime. For convenience a
default DataView is generated for the developer for customization.

In the analysis part, the application needs to display some statistical information, which
is calculated from several columns and which is shown in some dynamically generated
extra columns as shown in Figure 4 .

Figure 4. The Data View.


112

Some of the data columns needed for these calculations were in different parent and
child tables. Unfortunately it was not possible join two tables in the dataset to show up
in a single DataGrid.(for example, by using the DataSet.Relations property).To further
clarify the situation say I have two Parent & child tables Table1(id,columnA,columnB)
and Table2(id,columnC,columnD) and I want resulting datagrid columns to be view like
(columnA , columnB , columnC , columnD). It is similar to the situation if I had wrote a
sql query like

select a.id , a.columnA , a.columnB , b.[columnC] , b.[columnD]


From Table1 a , Table2 b
where a.id =b.id.

It is important to understand that DataView is not equivalent to a SQL VIEW . A


Dataset does not contain a query processor and has no mechanism to perform a join.

The other way to do it (most developers seems to suggest) is to simply create a new
datatable

That is typed the way you want it and manually moved the data from both datatables to
the new one. Also any data manipulation has to copy over to the original tables using
nested loops. This is a brute force method. It would be nice to hear if anyone comes up
with something else.

Finally more references were added to the schema file. But that is not the best
workaround. The reason that the columns could not be merged is found in the relational
programming model of the DataSets. The existing XML file uses nested child tables
instead of references. This is not (yet?) resolved by the .NET DataSets, so that
references are missing to cross-reference tables and to establish relationships.

XML Design Issue 2: "Use references in XML data files instead of nested child tables
to show up a joined table in a single DataGrid".

So the next change was to introduce references where needed.


113

Figure 5. Adding references to tables.

In our application we use the Date column as a filter criteria for the generated graphs in
the Crystal Report Engine. Thus in Figure 5 a Date column has been added to the
session table, which is a direct reference of the date column of the day table.

Reporting XML Data.

Having completed the data binding to Windows forms the next task was to generate the
summarized reports in both graphical and tabular forms. We have chosen the Crystal
Reports Engine (which is delivered with the VS.NET environment) with its powerful
dynamic reporting capabilities.

Crystal Reports for Visual Studio .NET offers the following three object models:

● The Engine Object Model.


● The Windows Forms Viewer Object Model.
● The Web Forms Viewer Object Model.

The top level Engine object model is the report document object. The report document
object offers sophisticated control over your object. It contains all the properties and
methods needed to interface with and customize a report. However it does not provide
the display of the reports.
114

This is where viewer objects and the report document objects come together. The
Windows Forms viewer allows you to view a report in a Windows application and the
Web Forms viewer does it for a Web application.

So we selected the Engine Object model together with the Windows Object Model to
accomplish the requirements. The Vb.NET CrystalDecisions.Windows.Forms
namespace in the CrystalDecisions.Windows.Forms.dll assembly provides support for
the Windows Forms Viewer control and its associated classes. It can also dynamically
update the report being hosted and interact with controls within a windows application.

When using the Crystal Report Engine you basically have two options for the selection
of data sources. The first one is passing the raw XML file, and the second is passing the
populated DataSet to the Crystal Report Engine.

When using the first approach you have to verify on every usage, that the XML file
contains correct data types (data validation). Otherwise Crystal Report Engine would
interpret the data types in the XML files differently (e.g. floats are used as strings),
which prevents the data from being processed further within Crystal Reports.

The second, recommended option is passing the already populated typed DataSets to
the Crystal Report Engine. This saves the runtime verification of data types. The content
and the scope of the report is determined at runtime according to the user selection of
the required report format. Crystal Reports provides template files for this. Figure 6
shows a sample report.
115

Figure 6. Crystal Report View.


116

UNIT V

Finding and Sorting Data in DataSets


Using the table’s Select method or the RowFilter property of a data view, the user can filter records in a
data table to make available only the required records. This is useful when the user wants to work with
different subsets of the records in a dataset table. To specify filter criteria, the user can use the same
expression syntax used to create column expressions. The filter expression is evaluated as a Boolean
expression; if the expression returns true, the record is included. A filter expression might look like the
following:

Price > 10.00

Filtering on Row State and Version


A dataset can maintain different versions of records in tables. When records are first filled in, the dataset
contains the original version of the record. If a record is changed, the dataset maintains a different
version — the current version — that reflects the changes. A property on the record indicates whether the
record is unmodified, updated, new, or deleted

A common use for filters is to specify only the current versions of records in the data table. If records
have been changed, there are two versions of a record–the current version reflecting the change and the
original version representing the record before any changes were made. Records are also flagged
according to their status: new, unchanged, deleted, or modified. A deleted record, for example, still exists
in the data table, but its raw-state flag has been set to delete.

Sorting
Sorting is similar to filtering, in that you specify a sort expression. A typical sort expression is simply the
name of the column to sort by. For example, to sort by the OrderDate column, the user msut specify the
sort expression OrderDate. However, the user can sort by the value of any expression, including calculated
values. If table’s Select method is called, the sort expression is passed as a parameter. If DataViews are
being used, the sort expression is to be specified as the value of the view’s Sort property.

Data View Manager


Individual DataViews can be defined to sort or filter the data in each DataSet table. If the DataSet contains
multiple tables, an alternative is to create a DataView manager (a DataViewManager object). The
DataView manager works something like a dataset-wide data view. It provides a single object that
manages a collection of DataViews, each of which is associated with a specific table in a dataset. To use
a DataView manager, the user must create and configure it in code. There is no design-time object that
can be added to a form or component. This means that controls are bound to the DataView manager in
code, as there is no design-time component to bind them to.

The following project will illustrate the filtering and sorting of the data.

1. Create a new Windows application project.


2. Add three labels, one DataGridView, one ComboBox and a button to the Form
3. And arrange them as shown in the screenshot below
4. Now go to the codes page and add the following codes.

Click here to view sample code


117
1. Create a SqlConnection object whose constructor will take the connectString as the parameter.
2. Create SqlDataAdapter whose constructor will take the SqlStatement and the connection object as
parameters.
3. Instantiating a DataSet and a DataView.
4. Call the fill method of the SqlDataAdapter and fill the DataSet.
5. Create a view.
6. To the ComboBox add the name of the table columns to be sorted on.
7. Instantiate a DataView object that will be based on the DataSet table
8. Call the sort method of dataview from within the EventHandler of ComboBox selectedIndexChanged.
9. Press F5 to execute the code.
10. The program allows the user to change the sort order just by choosing the fields in the combo box.
The screenshots of the program are given below.

The DataGridView before Sorting:

The DataGridView after sorting on Name:

In the same way table data can be filtered. In this case all the instructions given for the above case holds
good. The only change is in the EventHandler for the ComboBox. Instead of writing code for sorting, the
activity for filtering will be defined. The Additional lines of code for this demo is given below:
118
Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ComboBox2.SelectedIndexChanged

Dim filtStr As String

filtStr = Me.ComboBox2.Text

Label3.Text = "The Data is Filtered for all Names starting with alphabet " & filtStr

dv.RowFilter = "Name like ‘" & filtStr & "*’"

End Sub

Now press F5 to execute the program. The screenshot given below shows the initial Screen.

The Screenshot Below shows the Screen With filtered data:


119

The DataView provides several ways of sorting and filtering data in a DataTable:

● You can use the Sort property to specify single or multiple column sort
orders and include ASC (ascending) and DESC (descending) parameters.
● You can use the ApplyDefaultSort property to automatically create a sort
order, in ascending order, based on the primary key column or columns of
the table. ApplyDefaultSort only applies when the Sort property is a null
reference or an empty string, and when the table has a primary key defined.
● You can use the RowFilter property to specify subsets of rows based on
their column values. For details about valid expressions for the RowFilter
property, see the reference information for the Expression property of the
DataColumn class.
If you want to return the results of a particular query on the data, as
opposed to providing a dynamic view of a subset of the data, use the Find
or FindRows methods of the DataView to achieve best performance rather
than setting the RowFilter property. Setting the RowFilter property rebuilds
the index for the data, adding overhead to your application and decreasing
performance. The RowFilter property is best used in a data-bound
application where a bound control displays filtered results. The Find and
FindRows methods leverage the current index without requiring the index to
be rebuilt. For more information about the Find and FindRows methods,
see Finding Rows.
● You can use the RowStateFilter property to specify which row versions to view.
The DataView implicitly manages which row version to expose depending upon the
RowState of the underlying row. For example, if the RowStateFilter is set to
DataViewRowState.Deleted, the DataView exposes the Original row version of all
Deleted rows because there is no Current row version. You can determine which row
version of a row is being exposed by using the RowVersion property of the
DataRowView.
The following table shows the options for DataViewRowState.
DataViewRowState Description
options

CurrentRows The Current row version of all Unchanged, Added,


and Modified rows. This is the default.

Added The Current row version of all Added rows.

Deleted The Original row version of all Deleted rows.

ModifiedCurrent The Current row version of all Modified rows.


120

ModifiedOriginal The Original row version of all Modified rows.

None No rows.

OriginalRows The Original row version of all Unchanged, Modified,


and Deleted rows.

Unchanged The Current row version of all Unchanged rows.

Editing Data With ADO .NET-Web Services


Web services provide a way to run a service on the Web and access its methods
using standard protocols, including Simple Object Access Protocols (SOAP),
Extensible Markup Language (XML), Web Service Description Language (WSDL),
and Hypertext Transfer Protocol (HTTP). Technically, a web service is nothing more
than an application that exposes its interface to a client who wants to access the
service's abilities. The uses of a web service include validating credit cards,
searching for data in a database, inserting an order into a shopping cart, and
updating a guest list. The sky's the limit on what you can have your web service do
on your server. In the past, JavaBeans, ActiveX/Component Object Model (COM)
controls, and other nonstandard service components handled these services, which
required specialized formats to exchange data with the client. But web services
under .NET run by invoking methods in the service directly through HTTP or SOAP,
so someone wanting to run your web service from their computer at home can
simply send an HTTP call to your service, passing the parameter in a standard
Uniform Resource Locator (URL). I'll show you how to do this later in the article.

Three attributes make up a Web service:

● Discovery: First, you need to locate the Web service. You locate Web
service through the Discovery Service Protocol. The *.disco file stores
the protocol in your Visual studio (VS) .NET project. This file contains
reference to all the Web services under your Web site's virtual directory.
VS can automatically generate this file for you. The discovery file
(.vsdisco), an XML file, is used to identify searchable paths on the web
server used by the discovery process.
● Description: Once you have discovered your service, you need a way to
tell the client what methods, classes, and so on the web service has and
what wiring protocol (SOAP, HTTP, and so on) the services are using. You
do this through WSDL, an XML format. VS provides tools for generating
WSDL files automatically from your services.
121

● Wiring Protocol: Web services under .NET use two main protocols,
HTTP-post /HTTP-get and SOAP. HTTP-post and HTTP-get enable you
to send and receive information via a URL by passing and receiving
name value pair strings. Unfortunately, HTTP can only pass strings that
represent different data types. SOAP allows you to pass a richer type of
information, such as datasets.
Exploring Web Services and the .NET Framework Library

The .Net framework class library provides four namespaces that contain web service
classes. These namespaces are

System.Web.Services,System.Web.Services.Description,
System.Web.Services.Discovery, and System.Web.Services.Protocol.

The System.Web.Services namespace provides classes that enable you to build and
use web services. It has four classes. The WebService class defines the optional
base class for Web services, which provides direct access to an ASP.NET application.
Server, Session, User, and Context are some of its properties. WebMethodAttribute,
WebServiceAttribute, and WebServiceBindingAttribute are other classes of this
namespaces.

The System.Web.Services.Description namespace provides classes that enable you


to describe a WSDL.

The System.Web.Services.Discovery namespace provides classes that enable Web


service consumers to locate a Web service through discovery.

The System.Web.Services.Protocols namespace provides classes that define the


protocols used to transmit data between a client and a Web service.

Creating a Web Service in VS .NET

To understand Web services better, I'll show you to build a simple Web service. The
Web service will receive an order ID and then query the Northwind database's
Orders table for the correct order. It'll then return the order in a DataSet.

The first step in creating the web service is to select File > New > Project and
choose the ASP.NET Web service template, as shown in Figure 8-1.
122

Figure 8-1 Creating a new Web service project

This creates a Web service project on the MCB server. By default, local-host is
available as a Web server on your development machine. After the server name,
you give it a project name. In this sample, the project name is
OrderRetrievalService. VS .NET creates a new folder with the project name on the
Web server and keeps all project files under that folder. Clicking the OK button
creates the project.

If you look at the solution explorer, you'll notice a list of files created automatically
for the project, as shown in Figure 8-2. You won't be able to see some code and
resources files by default; they are hidden. You need to click on the show All Files
button of the Solution Explorer to view all the files (see Figure 8-2).
123

Figure 8-2 Files included in the web service project

First, the Web.config file is an XML file containing information on how to run the
service under ASP.NET. Second, the Global.asax and Global.asax.cs files enable you
to handle application-level events for the service. These event handlers include
event-handling pairs such as Application_Start-Application_End,
Session_start-Session_End, and Begin_Request-End_Request. You can view
Global.asax.cs by right clicking on the Global.asax file in the Solution Explorer and
choosing view code. Next, OrderRetrievalServices.vsdisco is an XML file containing
information for discovery of the service. You will actually need to generate an
OrderRetrievalService.disco file for your client to see the service (more on this
later).

Finally, the Service1.asmx file serves as the entry point into the service. The code
behind the service, Service1.asmx.cs is where you will place the method for
retrieving the order. Right-click on the Service1.asmx file in the Solution Explorer
and choose View Code from the pop-up menu, as shown in Figure 8-3.

Figure 8-3 Viewing the code in the Web service


124

See Listing 8-1 for the Web service code. Note that it looks like any other C#
component; it has a constructor, an InitializeComponent method, and a Dispose
method.

Listing 8-1. Initial Web service code in OrderRetrievalService.asmx.cs

public class Service1 : System.Web.Services.WebService


{
public Service1()
{
//CODEGEN: This call is required by the Asp.Net Web Services Designer
InitializeComponent();
}
#region Component Designer generate code
//Required by the Web Services Designer
private IContainer component = null;
/// <summary>
/// Required method for Designer support-do not modify
/// The contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
/// <summary>
/// Clean up any resources being used.
/// </summary>

protected override void Dispose(bool disposing)


{
if (disposing && component != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
// WEB SERVICE EXAMPLE
// The HelloWorld() example service return the string Hello World
// To build, uncomment the following lines then save and build the project
// To test this web service, press F5
// [Webmethod]
// public string HelloWorld()
// {
// return "Hello World";
//
}
125

Now I'll add database support to the Web service. Actually adding database
support to a web service is quite easy using ADO.NET. You can add ADO.NET
data components to a web service by just dragging the ADO.NET component from
the toolbox's Data tab to Web Forms. Similar to windows forms, you can also use
the Server Explorer to add database components to a Web service.

You can access different kinds of data sources in a similar fashion. The only thing
you change is the data provider and the connection string.

In this example, I'll use the Access 2000 Northwind database. I simply create a
connection and a data adapter to the Orders table in the Northwind database. You
can do this automatically through the .NET framework by simply dragging the
orders table from the server explorer onto the Service1.asmx.cs Design view, as
shown in Figure 8-4. In fact, as you can see from the figure, you can drag any
database table to the Web page.

Figure 8-4 Creating the OleDbDataAdapter from the Server Explorer

Drag the orders table to the page. This action adds a connection, data adapter, and
four command objects as follows:

private System.Data.OleDb.OleDbCommand oleDbSelectCommand1;


private System.Data.OleDb.OleDbCommand oleDbInsertCommand1;
private System.Data.OleDb.OleDbCommand oleDbUpdateCommand1;
private System.Data.OleDb.OleDbCommand oleDbDeleteCommand1;
private System.Data.OleDb.OleDbConnection oleDbConnection1;
private System.Data.OleDb.OleDbDataAdapter oleDbDataAdapter1;

Figure 8-5 shows the results in design view.


126

Figure 8-5 Results of dragging the orders table from the Server Explorer

If you drag the Orders table from SQL server database, the result will look like
Figure 8-6. The only difference is that SQL server uses the Sql data provider instead
of the OleDb data provider.

Figure 8-6 Results of dragging the SQL server orders table from the Server
Explorer
127

Now, the next step is to add a Web method to the project. You can use the Class
Wizard to add a method, or you can also add a method manually. For this
example, I'll use the Class Wizard to add a method.

To add a method to the project, open the class view from the main menu's View >
Class View option and right-click on the Service1 class and select Add > Add
Method, as shown in Figure 8-7.

Figure 8-7 Adding a new method to a Web service

The Add Method option opens the C# Method Wizard, which lets you add a method.
As you can see from Figure 8-8, I added a GetOrderFromDatabase method, which
returns a DataSet (type "DataSet" in the Return Type text box). This method also
takes one argument of integer type. You type the parameter name "OrderId" of
integer type and use the Add button to add the parameter. Now click Finish. This
process adds a method to the class, which looks like following:

public DataSet GetOrderFromDatabase(int OrderId)


{
return null;
}
128

Figure 8-8 Adding GetorderfromDatabase using the C# Method Wizard

Wait, this method is not a Web method yet. Before you write any code, you need to
add the [WebMethod] attribute at the beginning of this method to recognize it a
Web method.

Now you're going to add some code to the method. This method returns a DataSet
that will have records from the Orders table corresponding to an OrderId. Listing
8-2 shows the GetOrderFromDatabase method.

Listing 8-2. The Web Service method for obtaining an order from an
OrderId

[WebMethod]
public DataSet GetOrderFromDatabase(int OrderId)
{
DataSet ds = new DataSet("OrderSet");
oleDbDataAdapter1.SelectCommand.CommandText = "Select * from
Orders WHERE OrderID = " + OrderId.ToString();
oleDbDataAdapter1.Fill(ds, "Orders");
return ds;
}
129

As you can see from Listing 8-2, the method receives an OrderId from a client
and returns a DataSet to the client. It uses the DataAdapter to fill a DataSet with
the row containing that OrderId.

Note: You have to add a WHERE clause onto SelectCommand to filter the single
row of data. Also, you must make all exposed methods in the Web service public,
and they must contain a [WebMethod] attribute; otherwise, the client won't use
them.

Testing your Web Service

Now you are ready to build and test your web service. First, build the service using
the Build menu option and then start it in Debug mode. This will bring up the Web
service in your browser, as shown in Figure 8-9.

Figure 8-9 Initially running the Web service Service1.asmx.

As you see in figure 8-9, one method GetOrderFromDatabase is available in the


browser.
130

You can make this screen a bit more descriptive by adding a WebService
attribute to the top of the class and then adding descriptions to both the
WebService attribute and the WebMethod attribute. As you can see from listing 8-3,
I added a description to both.

Listing 8-3. Adding description to the WebService and WebMethod


attributes

[WebService(Description = "Working with orders in Northwind")]


public class Service1:System.Web.Services.WebService
{
[WebMethod(Description = "Retrieve an orders from Northwind")]

public DataSet GetOrderFromDatabase (int orderID)


{
.....
}

The service now looks like Figure 8-10.

Figure 8-10 The Web service after you add attributes

If you click on the link for the GetOrderFromDatabase method, you see the screen
on figure 8-11. This browser screen enables you to test the method by entering an
OrderID.
131

Figure 8-11 Testing the Web service's GetOrderFromDatabase method

After you click the invoke button, the browser returns the XML data representing
the DataSet, which contains the order with the order ID of 10248. Figure 8-12
shows a piece of the XML data representing the order and displayed by the browser.
132

Figure 8-12 The Order DataSet displayed by the browser in XML format

Note that because you're using a complex structure such as a DataSet for the
return parameter, you need to use SOAP with an XSD schema (which happens to be
the default wiring protocol) to transfer the data back to the client. The encoding of
the SOAP format is beyond the scope of this article, but if you're interested, you can
visit the World Wide Web Consortium (http://www.w3.org).

As you can see from figure 8-12, the default namespace for the DataSet xmlns is
http://tempuri.org. You can use the WebService attribute to specify the namespace
and description text for the XML Web service. As you can see, VS .Net doesn't
generate this attribute by default. You have to write it manually. If you are
specifying more than one property, you can separate them with a comma. For
example, the following code sets the namespace and the description properties of
the WebService attribute:

[WebService(Namespace = "http://servername/xmlwebservices/",
Description = "My Web Service")]
133

public class Service1 : System.Web.Services.WebService


{
// Implementation code.
}

SOAP, WSDL, Disco and UDDI-Instantiating


Interconnectedness engendered by the World Wide Web has created a pressure to create
applications that are interoperable and distributable over the network. The direction of effort is towards
creating applications that connect to each other regardless of the language or platform in which the
application was created.
Web services are externally exposed systems that allow applications to talk to each other and share
information over a network. The web service standards are built upon other standards such as HTTP or
XML and are not reliant upon any proprietary systems. The Web service is itself a collection of methods
that can be called from a remote location so that these methods accept and return parameters and
provide for a wide variety of functionalities that can be used internally in the application that is exposed
to the public.
The concept behind web services is not new. The ad hoc methods of tying applications together have
merely given place to organized methods of communications between applications. Standardized
specifications have also lowered costs and shortened development timelines.
Prior to the emergence of Visual Studio.NET in the market a number of technologies attempted to cater
to the needs of the Web based world. Let us briefly look at the various technologies that tried to address
these issues.
SOAP
Simple Object Access Protocol (SOAP) is a protocol that uses the XML to describe the data and
HyperText Transfer Protocol (HTTP) to transmit application data. The Web Service and the client
application must agree upon a common protocol to facilitate communication. SOAP is a standard
communication protocol for interchanging information in a structured format in a distributed
environment. Messaging is an example of information exchange between a client and a web service. The
calls made by a client application to a web method and the data returned by a web method to the client
are the messages that are actually exchanged. A SOAP packet is created when a web client makes a call
to the web method. This message contains the name of the web method and the parameters that are
needed for making a call to the web method in XML format. The Web method is invoked based on the
information available in the SOAP Packet
The System.Runtime.Serialization.Formatters.Soap namespace contains the
System.Runtime.Serialization.Formatters.Soap.SoapFormatter class, which can be used to serialize and
deserialize objects in the SOAP format. When building applications that use the types in this namespace,
a reference must be made to the System.Runtime.Serialization.Formatters.Soap.dll assembly. The COM+
SOAP service permits the publishing of a component as a XML Web Service. Clients can continue to
access the component using previous methods, but the component is also accessible using WSDL (Web
Services Description Language) and SOAP. We will see more of SOAP usage later in the lesson.
Disco and UDDI
The Web Service Discovery Tool (DISCO) is used to discover the URLs of XML Web Services located on a
Web server and saves documents related to each XML service on a local disk. The DISCO takes the URL
and discovers and publishes discovery documents (.wsdl, .xsd, .disco and .dicom files) as arguments.
Some of the options available for use with this tool are:
omain]:domain ecifies the domain name to use when connectin
a proxy server that requires authentication
134

save es not save the discovered document or results

ogo ppresses the Microsoft startup banner display

ut]:directoryName ecifies the output directory in which to save the


covered documents. Current directory is the
ault one.
assword]:password ecifies the password to use when connecting to
xy server
oxy:url ecifies the URL of the proxy server to use for
TP requests.
The following command is an example of how the tool can be used to search a specified URL for the
discovery of documents. The documents are then saved to the current directory. It will throw an error
message if it cannot find discoverable documents at the URL specified.
disco http://www.vbdotnetlearning.com/selflearningservie.disco
To specify a directory to save the documents you can use the /out option as shown below:
disco /out:VBa tutorial http://www.vbdotnetlearning.com
Universal Description, Discovery and Integration (UDDI) is a platform independent framework functioning
like a directory that provides a mechanism to locate and register web services on the internet. The web
service provider makes the web service available to the consumer by describing the web service using a
WSDL document and then registering the Web service in the UDDI Directory. The UDDI Directory contains
pointers to the Web service and the WSDL document for the Web service. After this is done the Client
Applications can discover the Web service using the UDDI Directory. The UDDI specification calls for
three elements as given below:
(1) White Pages — These provide business contact information
(2) Yellow Pages — These organize Web services into categories like usage billing service,
authorization service and so on.
(3) Green Pages –These Pages provide detailed technical information about individual services.
WSDL
Web Service Discovery Language (WSDL) is a markup language that describes the web service. In order
to use this Web service, the Client application developers need to know the methods exposed by the Web
service and the parameters to be passed to these methods. It is imperative that access to these
methodologies is available at development time and it is just this need that WSDL addresses.
● The Web service available for a given Web site
● The purpose for which these services can be used
● The types of parameters that need to be passed to a Web service
● The format used to access these Web services
● The URL at which a Web Service can be accessed

Invoking Web Services


Web services are one of the greatest technologies developed in the Internet world,
which could be used to connect businesses with each other and clients in a standard
way using XML (Extensible Markup Language), SOAP (Simple Object Access Protocol),
135

WSDL (Web Services Description Language) and UDDI (Universal Description,


Discovery and Integration).

XML is used for structuring the data, SOAP is used to transfer the data, WSDL is used
for describing the services and UDDI is used to get a list of services available. Web
service allows applications to communicate with each other without worrying about their
hardware systems, operating systems and programming languages.

Unlike the older model, web service does not provide a user interface but exposes the
business logic, which can be programmed, and hence the user is free to add his own
interface to the application.

Google is one of the websites which has provided a public web service allowing
applications to use features like search and spell checks. We shall now see how we can
use this service in our application using Visual Basic.NET.

But before we could access Google web APIs service we will have to create a Google
account and obtain a license key which shall allow us to run about 1000 automated
queries a day.

Getting Started

Now that you have received your license key, we shall create an application in Visual
Basic .NET to create a customized search and a spelling checker using Google Web
APIs Service.

Open your Visual Studio .NET, create a new Windows Application Project, which we
shall call googleapi, click OK.
136

Adding Web Reference to Google Web APIs


Service

We shall now add a Web Reference to Google Web APIs Service, well this is almost like
adding a reference to a COM/ActiveX object, but when we add a Web Reference we
now have access to all the XML web service on Google server. Open your Solution
Explorer, right click the References and click Add Web Reference, alternatively you
could select Project menu and click Add Web Reference.

In the window Add Web Reference type http://api.Google.com/GoogleSearch.wsdl in


the address bar (please make sure you type exactly as show, as this URL is case
sensitive)
137

After you enter the URL and press Enter and the Google Web Service is loaded you
should see a screen like Figure 2 also the Add Reference button is enabled, click Add
Reference button to add this web reference to our project.

In the Solution Explorer Window click on the Web Reference to see a Google Web
Reference, which we have added, lets rename that to Google by right clicking on it and
clicking Rename.
138

Create a User Interface as shown below with the flowing controls and given names

Source Code
Private Sub btn_Search_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btn_Search.Click

Dim MyLicenseKey As String ' Variable to Store the License Key


' Declare variable for the Google search service
Dim MyService As Google.GoogleSearchService = New _
Google.GoogleSearchService()
' Declare variable for the Google Search Result
Dim MyResult As Google.GoogleSearchResult
' Please Type your license key here
MyLicenseKey = "tGCTJkYos3YItLYzI9Hg5quBRY8bGqiM"
' Execute Google search on the text enter and license key
MyResult = MyService.doGoogleSearch(MyLicenseKey, _
txtSearch.Text, 0, 1, False, "", False, "", "", "")
' output the total Results found
lbl_TotalFound.Text = "Total Found : " & _
CStr(MyResult.estimatedTotalResultsCount)
End Sub

Finally

Now we have finished coding our application, run the application now and type some
text to search in the text box and click the Google Search button to see the number of
results found. Also try Google spell check.
139

Now you must have realized how simple it is to incorporate Google Web APIs Service in
your application, here are few things you could do with this service

● Issuing regularly scheduled search requests to monitor the web for new
information on a subject.
● Performing market research by analyzing differences in the amount of
information available on different subjects over time.
● Searching via non-HTML interfaces, such as the command line, pagers, or
visualization applications.
● Creating innovative games that play with information on the web.
● Add Google spell-checking to an application.

Creating Proxy Classes with WSDL


The .NET Framework SDK includes the Web Services Description Language tool, wsdl.exe.
This tool does not require the Web service client to use Visual Studio .NET. It can take a
WSDL file and generate a corresponding proxy class, which you can use to invoke the Web
service:

1. Open the Visual Studio .NET Command Prompt and navigate to the folder that
contains the WSDL file you created in the previous section using disco.exe.
2. Enter the following command to create a proxy class to call the AirportWeather Web
service: wsdl /language:CS /out:AirportWeatherProxy.cs AirportWeather.wsdl.
The tool reads the WSDL file and creates a new file named AirportWeatherProxy.cs.
3. Create a new Visual C# ASP.NET Web Application project (Example5_3). Add a
reference to System.Web.Services.dll.
4. Add the AirportWeatherProxy.cs file to the project by selecting File, Add Existing
Item.
140

5. Place a Label control, TextBox control (txtCode), Button control (btnGetWeather),


and ListBox control (lbResults) on the Web form. Change the Text property of the
label to Airport Code:.
6. Double-click the Button control and enter the following code to invoke the Web
service when the user clicks the Get Weather button:
private void btnGetWeather_Click(object sender,
System.EventArgs e) { // Connect to the Web service
AirportWeather aw = new AirportWeather(); // Invoke the
service to get a summary object WeatherSummary ws =
aw.getSummary(txtCode.Text); // And display the results
lbResults.Items.Clear(); lbResults.Items.Add(ws.location);
lbResults.Items.Add("Wind " + ws.wind);
lbResults.Items.Add("Sky " + ws.sky);
lbResults.Items.Add("Temperature " + ws.temp);
lbResults.Items.Add("Humidity " + ws.humidity);
lbResults.Items.Add("Barometer " + ws.pressure);
lbResults.Items.Add("Visibility " + ws.visibility); }
7. Build and run the project. Use the Web form to invoke the Web service.

The difference between this project and Example5_1 is that this code explicitly defines the
objects it uses rather than discovering them at runtime. The AirportWeather and
WeatherSummary objects are proxy objects that pass calls to the Web service and return
results from the Web service.

Table 5.2 shows some of the command-line options you can use with wsdl.exe. You can use
either the path to a local WSDL or Disco file, or the URL of a remote WSDL or Disco file
with this tool.

Option Meaning

/appsettingurlkey:DomainNam Specifies the domain name to use when connecting to a


e server that requires authentication.

/domain:DomainName Specifies the domain name to use when connecting to a


server that requires authentication.
/d:DomainName

/language:LanguageCode Specifies the language for the generated class. The


LanguageCode parameter can be CS (for C#, which is
/l:LanguageCode default), VB (for Visual Basic .NET), or JS (for JScript).

/namespace:Namespace Specifies a namespace for the generated class.

/n:Namespace

/out:Filename Specifies the filename for the generated output. If it's


not specified, the filename is derived from the Web
/o:FileName service name.
141

/password:Password Specifies the password to use when connecting to a


server that requires authentication.
/p:Password

/server Generates a class to create a server based on the input


file. By default, the tool generates a client proxy object.

/username:Username Specifies the username to use when connecting to a


server that requires authentication.
/u:Username

/? Displays full help on the tool.

/appsettingurlkey:DomainNam Specifies the domain name to use when connecting to a


e server that requires authentication.

/d:DomainName

Using Web References


As an alternative to using the Web Services Discovery and WSDL tools to create explicit
proxy classes, you can simply add a Web reference to your project to enable the project to
use the Web service. This is the same technique you used in the Example5_1 project.

In fact, the end result is no different when using the tools to create a proxy class and adding
a Web reference because, behind the scenes, the Web reference creates its own proxy
class. To see this, click the Show All Files toolbar button in Solution Explorer for the project
Example5_1, and then expand the Web References node. You'll see a set of files similar to
those in Figure 5.3.

Figure 5.3. When you add a Web reference, the proxy file is automatically generated.
142

The .wsdl file is the same file that is generated by running the Web Services Discovery
tool on the URL of the Web reference, and the .map file is the same as the .discomap
file generated by the Web Services Discovery tool. As you can see by opening this file, the
.cs file defines the proxy objects to be used with the Web service that is represented by this
Web reference. The major difference between this file and the proxy you generated with the
WSDL tool is that the autogenerated file uses a namespace based on the name of the Web
reference.

Use the WSDL proxy class tool (WseWsdl3.exe) to generate proxy code for a web service client
from a WSDL file. The .NET Framework SDK 2.0 WSDL.exe tool must be installed and
accessible.

Generate proxy code:


1. At the command prompt, run WseWsdl3.exe Soam.wsdl /type:webClient.
The command generates a file (Soam.cs) containing the proxy code, which consists of a
class that derives from the WebServicesClientProtocol class. Use the webClient type of
proxy class since the web service methods of the soapClient class type are limited to 0
or 1 parameters.
a. Do not specify the option "/order".
b. Check the Service References\soam\Reference.cs file in the C# project to ensure
that a fixed order is not specified. For example, the Reference.cs must
have:"[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema
.XmlSchemaForm.Unqualified)]", instead of
"[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.Xml
SchemaForm.Unqualified, Order=111)]".
2. Change sdRegisterAppResponse, sdViewSessionResponse, and sdViewTaskResponse
to sdRegisterAppResponse1, sdViewSessionResponse1, and sdViewTaskResponse1,
respectively in Soam.cs to avoid runtime errors:
Search for sdRegisterAppResponse, sdViewSessionResponse, and
sdViewTaskResponse in Soam.cs and replace them with sdRegisterAppResponse1,
sdViewSessionResponse1, and sdViewTaskResponse1, respectively. After this change,
.NET cannot get the return result of sdRegisterAppUpdate, but other methods work
properly.
3. Change "this.Url="http://www.platform.com/soam"; " in Soam.cs with the actual location
of the IBM® Spectrum Symphony SD, for example: this.Url="http://127.0.0.1:15050";

Creating a Web Service Project


Creating a Web service in Visual Studio .NET is very simple. ASP.Net server side technology
allows developers to create web services and the .NET framework provides a sophisticated set
of tools and code to consume web services.
143

In this exercise, we will build a simple web service �Hello World'. Most articles teach
about web services using the Hello World example. But few explain the technology
behind this web services example in detail. In this article we will learn both.

Let us start by creating the Hello world web service. We will create the web service using
asp.net and visual basic language. The IDE we will use is Visual Studio. Net. We can also create
a ASP.NET Web Service in C# programming language using visual studio. Net IDE.

To create the web service, open Visual Studio and select File-> New Web site from the menu.
Make sure Visual Basic is selected in the language box and HTTP in the location box. Select
ASP.NET Web service from the template list. Enter the name as http://localhost/HelloService as
shown in above figure and click OK.

Visual Studio 2005 will create a new web service project. A new virtual directory - HelloService -
will be created on your computer's Web server. This action also creates two files called
Service.asmx and service.vb. Please note that Visual Studio creates the entry point file with
.asmx extension and the other code behind the file with .vb extension. These files are
automatically added to the project, which we can see in a solution explorer.

The service.asmx and service.vb files represent a single web service. WebServices do not have a
visible interface and so, the design interface is empty. When we open the Service.asmx file, only
the following code is seen.

The service.asmx file serves as the entry point into the web service.

The other file, service.vb, is the code-behind file for the web service. We can write the
functionality of the web service in this file. The code-behind file imports the
System.Web.Services namespace. This namespace contains the classes that are required to
144

build and use Web services. We can view this file by switching to the code view for the
service.asmx file.

Note that a single project can contain multiple WebServices, each web service implemented by a
different class.

If we open the service.vb code-behind page, we can see the default code which is created by
vs.NET automatically, as listed below.

From the above code, we see that service is the class that contains all the code that implements
the web service methods. This is actually the name of the WebService; it's named after the class
and not after the project. The .vb and .asmx files together form the Code model for the web
services.

As we have already seen a web service is basically a class that sits on the server. Building a Web
Service with Visual Studio is as simple as writing a class. The class inherits from System. Web.
Services, and this base class includes all that is necessary to make the functions (methods) of
the class available on the Web. The Web Service class belongs to the system.Web.Services
namespace. This class provides direct access to built-in ASP.NET objects, such as Application
and Session. If an application does not require these objects, we can create a Web service
without deriving it from the Web Service class. So, Note that deriving from a web service base
class is optional.

Examining the Web Service Files

Service.asmx file

In the above line of code, @ WebService is the web processing directive that specifies a class
name, here service for a web service and the language used to create the web service is visual
basic.

Service.vb file
145

Explanation of the WebService attribute

The WebService attribute is an optional attribute that can be used to provide additional
information about the Web service. We can also use the WebService attribute to provide a
unique namespace for the web service. This namespace can be used by client applications to
resolve conflicts that may arise due to different Web services having methods with the same
name. The Webservice attribute can be provided before the Web service class declarations as
shown below.

The description of the Web service appears in the browser window when we try to access the
web service directly by providing the path.

The WebMethod Attribute

The methods that we want to expose to web service are marked with Webmethod attribute.

The Webmethod attribute enables us to call the web service methods remotely over the internet.
The syntax for applying the Webmethod attribute to a method is given below.

syntax for applying the Webmethod attribute to a method is given below.

The methods of this class don't return an HTML page, instead, they return one or more values,
packaged as XML documents.

Basically, if you can write a function, you can write a web method; it's that simple. The difference
between a class and a WebService class, is that the members of the WebService can be called
remotely.

VB.NET uses less than and greater than symbols to the <WebMethod> attribute to appear on the
line before the function definition.

From the above code, we note that class name is Service and method is HelloWorld.

If we want to change its name, we must rename the Service item in the Solution Explorer's
window, as well as the name of the class in the code.
146

Note that we can also create methods without preceding them with the WebMethod
attribute. However, these methods cannot be used to expose some functionalities to
applications. They can only be used by the other methods within the Web service class. We can
also write web services as plain text files with an extension of .asmx. We can use notepad to
develop the web service. The code is listed below. We will use this code example in our articles
on deployment and consuming a web service.

You might also like