0% found this document useful (0 votes)
5 views

net notes

.Net is a comprehensive framework that simplifies application development across various platforms, supporting over 50 programming languages. It includes essential components like the Common Language Runtime (CLR) and Base Class Library (BCL), which facilitate code execution, memory management, and interoperability among different languages. The Visual Studio .NET IDE enhances the development experience by providing tools for code management, debugging, and user interface design.

Uploaded by

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

net notes

.Net is a comprehensive framework that simplifies application development across various platforms, supporting over 50 programming languages. It includes essential components like the Common Language Runtime (CLR) and Base Class Library (BCL), which facilitate code execution, memory management, and interoperability among different languages. The Visual Studio .NET IDE enhances the development experience by providing tools for code management, debugging, and user interface design.

Uploaded by

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

Paper Name: .

Net programming

UNIT-I

.Net Framework:

 The .net framework is a new computing platform that simplifies applications development in the highly
distributed environment of the Internet.
 .Net framework is a new easy & extensive programming platform.
 .Net is a framework, it’s not a programming language. But it supports more than 50 languages.
 .Net is a operating system & platform independent.

.Net Services & Vision:

The .Net framework provides the following services……..


 It is a tool for developing software applications. And it is a runtime environment for software applications
to execute.
 .Net framework is a server infrastructure.
 This project is currently developing an open source version of C# compiler.
 It is value added intelligent software, which helps the developer to do less coding & work efficiently.
 Java is “One Language, many Platforms”, but .NET is “Many languages, one Platform”.
 .Net framework will enable developers to develop applications for various platforms like console
application, web applications, windows services & windows applications and web services.
 The .net splits an operating system platform be it… windows, Linux, MAC, whatever it may be it will take
into two layers.
1. Programming Layer
2. Execution Layer

Windows/Intel Combination(WinTel):

 This is the execution layer, .Net is a programming layer.


 It is totally owned and controlled by Microsoft.

.Net Framework Architecture:

 The Microsoft .Net framework is an integrative and manage environment for the development &
execution of the coding
 The .Net infrastructure consists of all the technologies that help in creating and running robust,
scalable and distributed applications.
 The .Net framework exists as a “Layer between .Net applications and Operating System”.
 The .Net framework consists of
1. Web Forms
2. Windows Forms
3. Console Applications
 Web forms are used in web based applications where as Windows forms are used in the windows
based applications for providing an interactive user interface.
 Console applications that can be executed from the command line.

Architecture of .NET Framework

VB.Net C++ C# Pearl ……….

V
Common Language Specification(CLS) I
S
U
A
Windows Forms L
Web forms Web Services (User Interface)
ASP .Net S
T
ADO.Net & XML U
D
I
O
Base Class Library
.
N
Common Language Runtime (CLR) E
T

Operating System

There are mainly two components are available:


1.Base Class Library
2.Common Language Runtime(CLR)
1.Base Class Library:
 .NET is totally OOPs language concepts, anything we want to do in .net we have to do with an
Object.
Ex: If you want to open a file you need to create an object.
 .Net class framework consists of class libraries that work with any .Net languages.
 This class library is built on the object nature of the runtime.
 System.io.file provides the access to a file on disk.
 .Net framework consists of class library that work with any .Net programming language such as
VB.net, C#, etc…
 The .net framework class library object facilitate types CTS that are common to all languages.
The Diagram for Basic Class Library Usability is as Follows..

Diagram Of Base Class Library

CCCk;fjl
CLR Application

System.io.file

Programming Language
Execution Platform……

Windows
File Packet Linux
System PC System File System

Common Language Runtime:


 CLR is the heart and soul of the .NET Framework.
 CLR is the Runtime environment in which the programs written in C#,VB and other
.NET languages are executed.
 It also supports the cross language interoperability.

ASP.NET
Unmanaged Code

VBRUN CLR
OS

ASP Managed Code

Infrastructure of CLR
The CLR provides the functionalities such as Exception handling, debugging and vesioning supports
to any .Net languages.
The CLR provides the number of sevices the includes,
 Loading & execution of programs.
 Memory isolation for applications
 Verification of Type safety
 Compilation of IL into native executable code
 Providing metadata
 Memory management(Automatic garbage collection)
 Security
 Managing Errors and Exception.
Components of CLR

Common language Runtime

Common Type System


Intermediate Language
Execution Support function
Security
Garbage Collection
Class Loader
Memory Loader

 The premier language for the CLR are VB, C# and c++ with managed extension.
 The code that is developed with a language compiler that targets the CLR is called managed
code.
 The code that is developed without considering the conventions and requirements of CLR is
called Unmanaged code.
 Unmanaged code executes in limited debugging and without garbage collection
process(manages the allocation and de allocation of memory for an application).
Common Type System:

 CTS helps the developer to develop applications in different languages.


 If .net languages share CTS means all the types used in applications share the same data type
defined under common language interface (CLI).
 The .net framework class library comprises Namespaces, which are contained in assemblies.

Namespace:

 This namespace helps to create the logical group of related Classes and Interfaces that can be
used by any language targeted by .Net Framework.
 Namespace allow you to organize the classes so that they can easily access in other applications.
Ex: System.console

(Namespace) . (Class)

 .NET framework uses a . (dot) as a delimiter between classes and namespaces.


 Framework Class Library (FCL) stores the namespaces.
 We can use the base classes in the system for many different tasks. They are as follows……..
 I/O Operation (Ex: System.io)
 String handling (Ex: System.string)
 Managing arrays, lists, etc
 Accessing files & file system
 Security (Ex: System.security)
 Windows messages
 Database management
 Evolution of mathematical function
 Drawing
 Managing errors & exceptions
 Connecting to the internet

Assemblies:
 An assembly is a deployable unit that contains all the information about the implementation of
classes and structures & Interfaces.
 In .net coding reusability is achieved through assemblies.
 Any coding in .net must be stored in assemblies on its compilation time.
 In addition to MSIL (MicroSoft Intermediate Language) code an assembly also contains 4
sections…..
1. Assembly metadata (manifest assembly)
2. Type metadata (data type information)
3. Program Code (coding in MSIL format)
4. Resources (files used in the programs)
 Assemblies are of 2 types………..
1. Private: It is used only in one particular application.
2. Public: It is used in different applications.

CTS Type Model:


Types/Object

Value Type Reference Type

ˇ Built-in Types Interface Types

Structures Pointer Types

Enumeration Self Describing Types

Arrays

Classes

User Types Boxed Types Delegates


 CTS defines the rules that all languages must follow.
 The CTS Type Model is basis for object model and hierarchy. The CTS provides the type
architecture, framework and guarantees the type safety.

 In .NET Types can be classified into 2 types. They are

1. Value Type: Allocates memory on Stack.-int, char, Boolean


2. Reference Type: Allocates memory on Heap.-->string, obj, class, interface

Value type hold data within its own memory location and own copy of data for operation.

Reference type means the variable contain a pointer to a memory location that holds data. CLR-

Architecture of CLR :-

Base class library support

Thread support COM Marshaller

Exception manager Security Engine

Type checker Debug Engine

Code manager IL into native compile Garbage collector

Class loader

Class loader:-
 Which loads the classes into CLR at the runtime?

Code manager:-
 Managing the code during execution.

MSIL into native compiles:-


 It converts the MSIL (Microsoft Intermediate Loudly) code to native compiles

MSIL = assembly level language code


Native code = .net source code

Garbage collector:-
 If supports the memory management and also supports unused memory at the
runtime.
Type check up:-
 Checks for type safety at runtime

Debug Engine :-
 If supports debugging at runtime and also allow the developer to debug different
types of application.

Exception Manager:-
 Handles the exception at runtime.

Security Engine:-
 If enforces the security rules at runtime.

Thread support:-
 It provides multithreading support to application.

COM Marshaler:-
 It supports marshalling of data between COM object

Base class Library:-


 It supports all base classes used for .net languageto support basic functionalities.

Executing the managed code:


MSIL (Microsoft Intermediate Language):
 It is set of instruction in which all the .net program are compiled.
 MSIL is related to assembly language code. It contains instruction for loading, storing,
initializing and calling method.

Exe Code

Class Loader

Base Class Library


Verify Test

JIT Compiler

Naive Machine Code


Executing the code:
Flowchart of managed code execution process

Source Code

Compiler

IL & metadata Metadata Engine

Linker Other Native Code

Exe Code

Class Loader Base Class Library

Verify Test

JIT Compiler

Native Machine Code

Runtime Manager

Output

Managed code:
 The CLR is responsible for managing the execution of code compiled for .net platform.
 The code statisfied the CLR at runtime in order to execute. This is referred to as managed
code.
 In the process of compiling and executing the managing code as follows,
i. When you compile a program develop in a language that targets the CLR instanced
of compiling the source code to machine code, the compiler translate source code to
MSIL code.
ii. In addition to translating the code into MSIL compiler also produce metadata, about
the program.
iii. Metadata contains the description of programs. Such as classes and interface used in
the program.
iv. In intermediate language and metadata and linked in an assembly via links.
v. The compiler creates the .exe (or) .dll file.
vi. When execute the .exe file the code from the base class library and send to the class
loader. The class loader loads the code into the memory.
vii. During JIT compilation the code is also checked for type safety.
viii. During the process of compilation the JIT compiler compiles only the code that is
require during the execution, instance of compiling the intermediate language code.
When an uncompelled method is invoked during the execution, the JIT compiler
converts the IL for that method into native code. This process same time in memory
to convert the IL into native code.
ix. After converting the IL into native code the converted code is send it to the .net
runtime manager.
x. The runtime manager executes the code and produces the output.

CLS (Common Language Specification):


 CLS defines rules and regulation that every languages that follow, which run under .net
framework.
 These rules guide to the third party compiler, designer and library builders.
 CLS is a fundamental set of language features supported by CLR of .NET framework.
 CLS was designed to support language construction commonly used by developers.
 CLS is a subset of CTS (Common Type System) and therefore language supporting the
CLS can use each class library.
 API (Application programming interface) that are designed and following the rules of
CLS and it can easily used by all language.
 ECMA – European Computer Manufacturers Association Standard has defines CLS,
this enforces the software development languages should interoperable between them.
 The code written in a CLS should be complaint with the code written in another CLS-
complaint Language.
 The language which follows these rules is called CLS- complaint language.
 The code supported by CLS-complaint language should be compiled into an IL code.
 The CLS-complaint languages are VB.Net,Visual C++.net, J#.net, C#.net etc.,
 The CLR Engine execute the IL code and this ensures the interoperability between CLs
Complaint languages.
 There are 2 common methods of CLS. They are as follows,
1. Public methods
2. Protected methods.

European Computer Manufacture Association(ECMA)

Common Language Runtime(CLS)

Common Type System Type Safety (TS)


(CTS)

Common Intermediate Language /


Microsoft Intermediate Language

ECMA standard under .NET framework


The Visual Studio .NET IDE:

 You don't actually need the Visual Studio .NET product to write applications in the Visual
Studio .NET language.
 The actual ability to run Visual Studio .NET code is included with the .NET Framework.
You could actually just write all of your Visual Studio .NET using a text editor such as
Notepad.
 However, by far the easiest way to write in Visual Studio .NET is by using the Visual
Studio.NET Integrated Development Environment, also known as the IDE.
 This is what you actually see when working with Visual Studio .NET – the windows, boxes,
etc. The IDE provides a wealth of features that are unavailable in ordinary text editors – such
as code checking, visual representations of the finished application, and an explorer that
displays all of the files that make up your project.

Windows in the Visual Studio .NET IDE:


At this point, you can see that the various windows in the IDE are beginning to show their purposes,
and we will take a brief look at them now before we come back to the Try It Out.
Note that if any of these windows are not visible on your screen, you can use the View menu to
select and show them.
Also if you do not like the location of any particular window you can move it by clicking on its title
bar (the blue bar at the top) and dragging it to a new location. The windows in the IDE can float
(stand out on their own) or be dockable (as they appear above).
Server Explorer
The Server Explorer gives you management access to the servers on your network. Here you can
create database connections, and view the services provided by the available servers.

Toolbox
The Toolbox contains reusable components that can be inserted into your application. These can
range from buttons to data connectors to customized controls either purchased or developed
yourself.

Design Window
The Design window is where a lot of the action takes place. This is where you will draw your user
interface and write your code. This window is sometimes referred to as the Designer.

Solution Explorer
The Solution Explorer window contains a hierarchical view of your solution. A solution can contain
many projects while a project contains code and code references that solve a particular problem.
Class View
The Class View window (shown as a tab with the Solution Explorer) gives you a tree view of the
classes in your program and shows the properties and methods that each contains. A class is code
file that groups data and the functions that manipulate it together into one unit. A property is data,
and a method is a function or subroutine.

Properties
The Properties window shows what properties the selected object makes available. Although you
can set these properties in your code, sometimes it is much easier to set them while you are
designing your application. You will notice that the File Name property has the value Form1.vb.
This is the physical file name for the form's code and layout information.

Task List
The Task List window highlights any errors encountered when you try to run your code. Clicking on
the item in this window will take you to the line of code containing the error.

Output
When you run your code the progress made in reading it (or compiling it) is registered via messages
posted in the Output window.
Dynamic Help
The Dynamic Help window displays a list of help topics that relate to whatever in the IDE has focus.
If you click on the form in the Design Window and then open Dynamic Help, you will see a list of
help topics relating to forms.
The Toolbox:
 The Toolbox is accessed via the View | Toolbox menu option, the Toolbox icon on the
Standard menu bar, or by pressing Ctrl + Alt + X.
 The Toolbox contains a tabbed view of the various controls and components that can be
placed onto your form.
 Controls such as textboxes, buttons, radio buttons, and drop-down boxes can be selected and
then drawn onto your form. For the HelloUser application, we will only be using the controls
on the Windows Forms tab:

 Here we can see a listing of standard .NET controls for Windows forms. The down arrow
button to the right of the Clipboard Ring tab title actually scrolls the Windows Forms control
list down as there are too many to fit in otherwise.
 The up arrow button on the Windows Forms tab scrolls the list up. Note that the order in
which your controls appear may be different.
 Controls can be added to your forms in any order, so it does not matter if we add the label
control after the textbox or the buttons before the label.

Modified Hungarian Notation:


 You may have noticed that the names given to the controls look a little funny. Each name is
prefixed with a shorthand identifier describing the type of control it is. This makes it much
easier to understand what type of control we are working with when we are looking through
code.
 For example, say we had a control called simply Name, without a prefix of lbl or txt, we would
not know whether we were working with a textbox that accepted a name or a label that
displayed a name.
 How about if we left our application for a month or two, and then came back to it to make some
changes? When working with other developers, it is very important to keep the coding style
consistent.
 One of the most commonly used styles used for controls within application development in
many languages is Modified Hungarian notation.
 The notion of prefixing control names to identify their use was brought forth by Dr. Charles
Simonyi. He worked for the Xerox Palo Alto Research Center (XPARC), before joining
Microsoft.
 He came up with short prefix mnemonics that allowed programmers to easily identify the type
of information a variable might contain. Since Dr. Simonyi is Hungarian, and the prefixes make
the names look a little foreign, the name Hungarian Notation stuck.
 Since the original notation was used in C/C++ development, the notation for Visual Basic .NET
is termed Modified.
 Here is a table of some of the commonly used prefixes that we shall be using in this book:

Control Prefix
Button btn
ComboBox cbo
CheckBox chk
Label lbl
ListBox lst
MainMenu mnu
RadioButton rdb
PictureBox pic
TextBox txt

 Hungarian Notation can be a real time-saver when looking at code someone else wrote, or at
code that you have written months past. However, by far the most important thing is to be
consistent in your naming.
 When you start coding, pick a convention for your naming. It is recommended that you use the
de facto standard Modified-Hungarian for Visual Basic .NET, but it is not required.
 Once you pick a convention, stick to it. When modifying someone else's code, use theirs. There
is very little code that is ever written, put into production and then forgotten.
 A standard naming convention followed throughout a project will save countless hours when
the application is maintained.

The Code Editor:


 Now that we have the HelloUser form defined, we have to add some code to actually make it do
something interesting. We have already seen how easy it is to add controls to a form.
 Providing the functionality behind those on-screen elements is not much more difficult. To add
the code for a control, just double-click on it. This will open the code editor in the main
window:
 Notice that an additional tab has been created in the main window. Now we have the Design tab
and the code tab. We drew the controls on the Design tab, and we write code on the code tab.
One thing to note here is that we have not created a separate file for the code.
 The visual definition and the code behind it both exist in the same file: HelloUser.vb. This is
actually the reason why building applications with Visual Basic .NET is so slick and easy.
 Using the Design view you can visually lay out your application, and then using the Code view
add just the bits of code to implement your desired functionality.
 You will also notice that there are two pull-downs at the top of the window. These provide
shortcuts to the various parts of our code. If you pull down the one on the left, Form1
(HelloUser), you will see a list of all of the objects within our application. If you pull down the
one on the right, (Declarations), you will see a list of all of the defined functions or subroutines.
 If this particular form had a lot of code behind it, these pull-downs would make navigating to
the desired area very quick – jumping to the selected area.

Adding Code To The HelloUser Project:
1. To begin adding the necessary code, click on the Design tab to show the form again. Then double-
click on the OK button. The code window will reopen with the following code. This is the shell of
button's Click event and is the place where we enter code that we want to be run when we click on
the button. This code is known as an event handler, and sometimes is also referred to as an event
procedure:

Private Sub OK_Click(ByVal sender As SystemObject, ByVal e As _


System.EventArgs) Handles OK_Click
End Sub

Due to the typographic constraints in publishing, it is not possible to put the Sub declaration
on one line. Visual Basic .NET allows you to break up lines of code by using the underscore
character (_) to signify a line continuation. The space before the underscore is required. Any
whitespace preceding the code on the following line is ignored.
Sub is an example of a keyword. In programming terms, a keyword is a special word that is used to
tell Visual Basic .NET to do something special. In this case, it tells Visual Basic .NET that this is a
procedure. Anything that we type between the lines Private Sub and End Sub will make up the event
procedure for the OK button.

2. Now add the highlighted code into the procedure:

Private Sub OK_Click(ByVal sender As SystemObject, ByVal e As _


System.EventArgs) Handles OK_Click
'Display a message box greeting the user
MessageBox.Show("Hello, " & txtName.Text & _
"! Welcome to Visual Basic .NET.", _
"HelloUser Message")
End Sub

3. After you have added the code, go back to the Design tab, and double-click on the Exit button.
Add the highlighted code to the ExitButton_Click event procedure.

Private Sub ExitButton_Click(ByVal sender As SystemObject, ByVal e As _


System.EventArgs) Handles ExitButton_Click
'End the program
Me.Dispose()
End Sub
You may be wondering what Me is. Me refers to the form. Just like the pronoun, me, it is just a
shorthand for referring to oneself.

4. Now that the code is finished, the moment of truth has arrived and we can see our creation. First
though, save your work by using File | Save from the menu, or by clicking the disk icon on the
toolbar.

5. Now click on the Start button on the toolbar. You will notice a lot of activity in the Output
window at the bottom of your screen. Providing you haven't made any mistakes in entering the code,
this information just lets you know what files are being loaded to run your application.

It's at this point that Visual Studio .NET will compile the code. Compiling is the activity of taking
the Visual Basic .NET source code that you've written and translating it into a form that the
computer understands. After the compilation is complete, Visual Studio .NET will run (also known
as execute) the program and we'll be able to see the results.

6. When the application loads you will see the main form. Enter a name and click on OK (or press
the Alt+O key combination):

7. A window known as a message box appears, welcoming the person whose name was entered in
the textbox to Visual Basic .NET – in this case Deborah:

8. After you close the message box by clicking on its OK button, click on the Exit button on our
form. The application will close and you will be brought back to the Visual Basic .NET IDE.

Using the Help System:


The Help system included with Visual Basic .NET is an improvement over Help systems in
previous versions. As you begin to learn Visual Basic .NET, you will probably become very familiar
with the Help system. However, it is worthwhile to give you an overview, just to help speed your
searches for information.
The Help menu appears as:
 As you can see this menu contains many more entries than the typical Windows application.
The main reason for this is the vastness of the documentation. Few people could keep it all in
their heads – but luckily, that's not a problem, as we can always quickly and easily refer to the
Help system. Think of it as a safety net for your brain.
 One really fantastic new feature is Dynamic Help. If you turn this option on (by selecting
Dynamic Help from the Help menu), a window will display a list of relevant topics for
whatever you may be working on. If you followed the default installation and have not
rearranged the IDE, the Dynamic Help is displayed as a tab behind Properties.
 Let's say for example, that we are working with a textbox (perhaps the textbox in the HelloUser
application) and want to find out some information; we just select the textbox on our form and
we can see all the help topics that pertain to textboxes:

 The other help commands in the Help menu (Contents, Index, and Search), function just as they
would in any other Windows application.
 The domain of help topics to search and display is defined by the profile that we defined at
installation. However, the Edit Filters… menu option allow you to further focus what types of
documentation to include in the search.
VISUAL BASIC . NET

 Visual Basic .NET (VB.NET) is a multi-paradigm, high level programming


language, implemented on the .NET Framework.
 VB.Net is a simple, modern, object-oriented computer programming language
developed by Microsoft to combine the power of .NET Framework
 Microsoft launched VB.NET in 2002 as the successor to its original Visual Basic
language.
 Before Visual Basic 1.0 was introduced to the world in 1991, developers had to be well
versed in C++ programming, as well as the rudimentary building blocks (Windows API)
of the Windows system itself.
 This complexity meant that only the dedicated and properly trained were capable of
turning out software that could run on Windows.
 Visual Basic changed all of that, and it has been estimated that there are now as many
lines of production code written in Visual Basic as in any other language.
 Visual Basic changed the face of Windows programming by removing the complex
burden of writing code for the user interface (UI).
 By allowing programmers to draw their own UI, it freed them to concentrate on the
business problems they were trying to solve. Once the UI is drawn, the programmer can
then add code to react to events.
 Visual Basic has also been extensible from the very beginning. Third-party vendors
quickly saw the market for reusable modules to aid developers. These modules, or
controls, were original referred to as VBXs (named after their file extension).
 If you didn't like the way a button behaved you could either buy or create your own.
However, these controls had to be written in C or C++. Database access utilities were
some of the first controls available.
 When Microsoft introduced Visual Basic 3.0, the programming world changed again.
Now you could build database applications directly accessible to users (so called front-
end applications) completely with Visual Basic.
 There was no need to rely on third-party controls. Microsoft accomplished this task with
the introduction of the Data Access Objects (DAO), which allowed programmers to
manipulate data with the same ease as manipulating the user interface.
 Versions 4.0 and 5.0 extended the capabilities of version 3.0 in order to allow
developers to target the new Windows 95 platform. Crucially they also made it easier
for developers to write code, which could then be manipulated in order to be used by
other language developers.
 Version 6.0 gave us a new way to access databases with the integration of ActiveX Data
Objects (ADO). ADO was developed by Microsoft to aid web developers using Active
Server Pages to access databases.
 With all of the improvements to Visual Basic over the years, it ensured its dominant
place in the programming world. It helps developers write robust and maintainable
applications in record time.
 With the release of Visual Basic .NET, many of the restrictions that used to exist have
been obliterated.
 In the past, Visual Basic has been criticized and maligned as a "toy" language, as it did
not provide all ofthe features of more sophisticated languages such as C++ and Java.
 Now, Microsoft has removed these restrictions and made Visual Basic .NET a very
powerful development tool. Visual Basic .NET has become a great choice for
programmers of all levels.

VISUAL BASIC .NET IDE


An integrated development environment (IDE), also known as integrated design environment
and integrated debugging environment, is a type of computer software that assists computer
programmers to develop software. In the case of Visual Basic .NET, that IDE is Visual Studio.
IDE Contents:-
The Visual Studio IDE consists of several sections, or tools, that the developer uses while
programming. As you view the IDE for a new project you generally have three sections in view:
 The Toolbox on the left
 The Solution Explorer on the right
 The Code / Design view in the middle

Toolbox
The Toolbox is a palette of developer objects, or controls, that are placed on forms or web
pages, and then code is added to allow the user to interact with them. An example would be
TextBox, Button and ListBox controls. With these three controls added to a Windows Form object
the developer could write code that would take text, input by the application user, and added to the
ListBox after the button was clicked.
Solution Explorer
This is a section that is used to view and modify the contents of the project. A Visual Studio
Windows Application Project will generally have a Form object with a code page, references to
System components and possibly other modules with special code that is used by the application.
Properties Windows
The properties windows shows all the control (like textbox) properties to be change at design
time. Most of these properties can be change at run time with some code, but basically most of this
properties change the way the control is display on your application.
Code / Design view
This is where the magic takes place. Forms are designed graphically. In other words, the
developer has a form on the screen that can be sized and modified to look the way it will be
displayed to the application users.
Important Features:-
1. One IDE for all .NET Projects
Visual Studio .NET IDE provides a single environment for developing all types of
.NET applications. Application’s range from single windows applications to complex n-tier
applications and rich web applications.
2. Option to choose from Multiple Programming Languages
You can choose the programming language of your choice to develop applications
based on your expertise in that language. You can also incorporate multiple programming
languages in one .NET solution and edit that with the IDE.
3. IDE is Customizable
You can customize the IDE based on your preferences. The My Profile settings
allow you to do this. With these settings you can set the IDE screen the way you want, the
way the keyboard behaves and you can also filter the help files based on the language of
your choice.
4. Built-in Browser
The IDE comes with a built-in browser that helps you browse the Internet without
launching another application. You can look for additional resources, online help files,
source codes and much more with this built-in browser feature.
When we open VS .NET from Start->Programs->Microsoft Visual Studio .NET-
Microsoft Visual Studio .NET the window that is displayed first is the Start Page which is
shown below. The start Page allows us to select from the most recent projects (last four
projects) with which we worked or it can be customized based on your preferences.
This center window of the IDE is also where developers write the code that makes
everything in the application work. The code is written in modules, or files, that are either
connected to an object (Forms) or called specifically when needed.
The Integrated Development Environment (IDE) shown in the image below is what we actually
work with. This IDE is shared by all programming languages in Visual Studio. You can view the
toolbars towards the left side of the image along with the Solution Explorer window towards the
right.

New Project Dialogue Box


The New Project dialogue box like the one in the image below is used to create a new
project specifying its type allowing us to name the project and also specify its location on the disk
where it is saved. The default location on the hard disk where all the projects are saved is
C:\DocumentsandSettings\Administrator\MyDocuments\VisualStudioProjects.

Following are different templates under Project Types and their use.
1. Windows Application: This template allows creating standard windows based applications.
2. Class Library: Class libraries are those that provide functionality similar to Active X and
DLL by creating classes that access other applications.
3. Windows Control Library: This allows creating our own windows controls. Also called as
User Controls, where you group some controls, add it to the toolbox and make it available to
other projects.
4. ASP .NET Web Application: This allows creating web-based applications using IIS. We
can create web pages, rich web applications and web services.
5. ASP .NET Web Service: Allows creating XML Web Services.
6. Web Control Library: Allows creating User-defined controls for the Web. Similar to user
defined windows controls but these are used for Web.
7. Console Application: A new kind of application in Visual Studio .NET. They are command
line based applications.
8. Windows Service: These run continuously regardless of the user interaction. They are
designed for special purpose and once written, will keep running and come to an end only
when the system is shut down.
9. Other: This template is to develop other kinds of applications like enterprise applications,
database applications etc.

The Menu:
Visual Studio .NET's menu is dynamic, meaning that items will be added or removed depending on what you
are trying to do. While we are still looking at the Get Started page, the menu bar will only consist of the File,
Edit, View, Tools, Window, and Help menus.

File
It seems every Windows program has a File menu. It has become the standard where you
should find, if nothing else, a way to exit the application. In this case, you can also find ways of opening and
closing single files and whole projects.
Edit
The Edit menu provides access to the items you would expect: Undo, Redo, Cut, Copy, Paste, and Delete.
View
The View menu provides quick access to the windows that make up the IDE, such as the Solution Explorer,
Properties window, Output window, Toolbox, etc.
Project
The Project menu allows you to add various extra files to your application.
Build
The Build menu becomes important when you have completed your application and want to be able to run it
without the use of the Visual Basic .NET environment
Debug
The Debug menu allows you to start and stop running your application within the Visual Basic .NET IDE. It
also gives you access to the Visual Studio .NET debugger. The debugger allows you to step through your
code while it is running to see how it is behaving.
Data
The Data menu helps you use information that comes from a database. It only appears when you are working
with the visual part of your application (the [Design] tab will be the active one in the main window), not
when you are writing code. Chapters 15 and 16 will introduce you to working with databases.
Format
The Format menu also only appears when you are working with the visual part of your application. Items on
the Format menu allow you to manipulate how the windows you create will appear to the users of your
application.
Tools
The Tools menu has commands to configure the Visual Studio .NET IDE, as well as links to other external
tools that may have been installed.
Window
The Window menu has become standard for any application that allows more than one window to be open at
a time, such as Word or Excel. The commands on this menu allow you to change the physical layout of the
windows in the IDE.
Help
The Help menu provides access to the Visual Studio .NET documentation. There are many different ways to
access this information (for example, via the help contents, an index, or a search). The Help menu also has
options that connect to the Microsoft Web site to obtain updates or report problems.
R
The Toolbars:
 There are many toolbars available within the IDE, including Formatting, Image Editor, and Text
Editor, which you can add to and remove from the IDE via the View | Toolbars menu option.
 Each one provides quick access to often-used commands, preventing you from having to navigate
through a series of menu options.
 For example, the leftmost icon on the toolbar shown below (New Project) is available from the
menu by navigating to File | New | Project.

The default toolbar (called Standard) appears at the top of the IDE as:
Tool Bars
 The toolbar is segmented into groups of related options, which are separated by a vertical bar.The
first five icons provide access to the commonly used project and file manipulation options
available through the File and Project menus, such as opening and saving files.
 The next group of icons is for editing (Cut, Copy, and Paste).The third group of icons is for editing
and navigation. The navigation buttons replicate functionality found in the View menu and allow
us to cycle through the tabs at the top of the main window.
 The fourth group of icons provides the ability to start your application running (via the blue
triangle) and to specify build configurations.
 There are times when you want certain parts of your code only to appear in a debug version, a bit
like a rough draft version of your application.
 For example, you may have code in your application that is only useful for tracking down problems
in the application.
 When it is time to release your application to the world, you will want to exclude this code by
setting the Solution Configurations settings to Release. You can also access the functionality
offered by this group via the Build and Debug menus.
 The next section allows you to locate parts of your code quickly. The simplest way to search is to
type some text into the Find textbox and hit Enter. If the text is found, it will be highlighted in the
central window.
 The Find in Files option allows you to specify more sophisticated searches, including matching the
case of the text, looking in specific files or projects, and replacing the found text with new text.
 The search functionality can also be accessed via the Edit | Find and Replace menu option.
 The next group of icons provides quick links back to the Solution Explorer, Properties window,
Toolbox, and Class View. If any of these windows are closed, clicking the appropriate icon will
bring it back into view.
Toolbox Window

 The toolbox window is the window that gives us access to all controls, components, etc. As you can
see from the image below, the toolbox uses tabs to divide it's contents into categories (Data,
Components, Windows Forms and General).
 The Data tab displays tools for creating datasets and making data connections, the Windows Forms
tab displays tools for adding controls to forms, the General tab is left empty by default, the
Clipboard Ring tab displays recent items stored in the clipboard and allows us to select from them.
Solution Explorer Window

The Solution Explorer window gives an overview of the solution we are working with and lists
all the files in the project. An image of the Solution Explorer window is shown below

Server Explorer Window

The Server Explorer window is a great tool that provides "drag and drop" feature and helps
us work with databases in an easy graphical environment. For example, if we drag and drop a
database table onto a form, VB .NET automatically creates connection and command objects that
are needed to access that table. The image below displays Server Explorer window.
Intellisense

Intelligence is what that is responsible for the boxes that open as we type the code.
IntelliSense provides a list of options that make language references easily accessible and helps us to
find the information we need. They also complete the typing for us. The image below displays that.

Code Designer Window


Code Designers like the image below allows us to edit and write code. This is the window
that opens when we double-click on a form or any control. This is the place where we write all the
code for the application. Notice the two drop-down list boxes at the top of the code window in the
image below. The left box allows us to select the object's code we are working with and the right
box allows us to select the part of code that we want to work.
Properties Window

The properties window allows us to set properties for various objects at design time. For
example, if you want to change the font, font size, back color, name, text that appears on a button,
textbox etc, you can do that in this window. Below is the image of properties window. You can view
the properties window by selecting View->Properties Window from the main menu or by
pressing F4 on the keyboard.

Output Window

The output window as you can see in the image below displays the results of building and
running applications.

Variables:

Variables in VB.net 2008 are used to store values and also they have a datatype and a unique name.
Naming Convention:

Variables in Visual Basic should start with an alphabet or a letter and should not contain any special
characters like %,&,!,#,@ or $. The variable should not exceed 255 characters.

Scope of Variables: A variable declared in the general declaration of a form can be used in all the
procedures. Variables declared inside a procedure will have a scope only inside the procedure, so
they are declared using the Dim keyword.
All variables have:
 Data type – kind of data the variable can contain

 Name – An identifier the programmer creates to refer to the variable

 Value – Every variable refers to a memory location that contains data. This value can be
specified by the programmer.

Declaring and Initializing Variables


• Before declaring a variable, the programmer must specify its data type
• VB .NET has nine primitive data types:
 Data types for numeric data without decimals

• Byte, Short, Integer, Long


 Data types for numeric data with decimals

• Single, Double, Decimal


 Other data types

• Boolean, Char
 To declare a VB .NET variable, write:

o Keyword “Dim”

o Name to be used for identifier

o Keyword “As”

o Data type

• Example:
‘declare a variable
Dim i As Integer
• A value can be assigned by the programmer to a variable
• Assignment operator (=) assigns the value on the right to the variable named on the left side
• Example:
' populate the variable
i=1
• The code for both declare and initialize a variable can be written in one statement:
' declare a variable
Dim i As Integer = 1
• Several variables of the same data type can be
declared in one statement:
Dim x, y, z As Integer
Example
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim c As Integer
c = Val(TextBox1.Text) + Val(TextBox2.Text)
TextBox3.Text = c
End Sub
End Class
Description:

In the above example, Dim statement is used to declare variables, c that can be used within the sub
procedure.

Data Types

Data Type in Visual Basic.net 2008 defines the type of data a programming element should be
assigned, how it should be stored and the number of bytes occupied by it.
 Integer

 String

 Single

 Double

 Boolean

 char.

Data Type Storage Size(bytes)

Boolean 2

Byte 1

Char 2

Date 8
Decimal 16

Single 4

Double 8

Short 2

Integer 4

Long 8

String Variable

Boolean

 Boolean is really a flag and not a numeric data type. The storage size is 16 bits in VB6 and
varies by platform in .NET.

Integer and Long

 Integer and Long have the same name and type character in VB6/VBA and VB.NET, but
they are different data types altogether. To stay clear one can use Int16, Int32 and Int64 in
.NET.

Currency

 Currency is a 64-bit integer divided by 10000. It is only available in VB6/VBA. In VB.NET


one can replace it with Decimal, which provides more capability.

LongLong

 Introduced with Office 2010, LongLong is a 64-bit signed integer that is available in VBA7
running on a 64-bit platform. It is unsupported in VB6, VBA6 and on 32-bit platforms.

Decimal

 Decimal is a signed 96-bit integer, which is divided by a scaling factor. The scaling factor
varies from 1 to 1E+28. A Decimal can represent 29 decimal digits: integers and decimal
numbers with max 28 decimal places. The binary representation consists of a 1-bit sign, a
96-bit integer number and the scaling factor. VB6 supports Decimal with the Variant data
type. You cannot declare a variable to be of type Decimal. You can, however, create a
Variant whose subtype is Decimal using the CDec function.
Single

 The smallest non-zero Single is ±1.401298E-45.


 VB6: The maximum Single is 3.4028235E+38, but it rounds down to 3.402823E+38
when displayed. The latter is also the maximum Single literal you can write in VB6 code.
 .NET: NaN, Positive Infinity and Negative Infinity are special values of Single.

Double

 The smallest non-zero Double is ±4.94065645841247E-324 in VB6 and


±4.94065645841246544E-324 in .NET.
 VB6 stores max 1.7976931348623157E308, but this round down to
1.79769313486231E+308 when displayed. The latter value is also the maximum literal
number you can write in VB6 code
 .NET: NaN, PositiveInfinity and NegativeInfinity are special values of Double.

Constants in VB.NET
Constants in VB.NET is declared using the keyword Const. Once declared, the value of these
constants cannot be altered at run time.
Syntax:

[Private | Public | Friend | Protected Friend ]


Const constName As datatype = value

In the above syntax, the Public or Private can be used according to the scope of usage. The Value
specifies the unchangable value for the constant specifed using the name constName.

 Constatnt doesn’t change the value


 Constants are processed faster than variables

Example:
Public Class Form1
Public Const PI As Double = 3.14159
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim r, a As Single
r = Val(TextBox1.Text)
a = PI * r * r
TextBox2.Text = a
End Sub
End Class
Description:

In the above example, a constant PI is declared as Public so that it can be used anywhere in the
class.

Array:

 Array is a collection of homogeneous data element that can be stored in a consecutive

memory location under a common variable name .


 In other words, An array stores a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type.
 All arrays consist of contiguous memory locations. The lowest address corresponds
to the first element and the highest address to the last element.

Arrays in VB.net are declared using the Dim statement, but by using the access specifiers Public,
Private, Static, Protected the scope of usage of arrays can be controlled within the code.

Following are the basic types of arrays used in VB.net

 Single Dimensional Array


 Multi Dimensional Array
 Dynamic Arrays

One Dimensional Array

Creating 1D Arrays in VB.Net

To declare an array in VB.Net, you use the Dim statement. For example,

 Dim intData(30) ' an array of 31 elements


 Dim strData(20) As String ' an array of 21 strings
 Dim twoDarray(10, 20) As Integer 'a two dimensional array of
integers
 Dim ranges(10, 100) 'a two dimensional array
You can also initialize the array elements while declaring the array. For example,

 Dim intData() As Integer = {12, 16, 20, 24, 28, 32}


 Dim names() As String = {"Karthik", "Sandhya", "Shivangi",
“shwitha", "Somnath"}
 Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}

The elements in an array can be stored and accessed by using the index of the array. The following
program demonstrates this:

Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '
For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module

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

Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110

Multi-Dimensional Arrays

VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular arrays.

 You can declare a 2-dimensional array of strings as:

 Dim twoDStringArray(10, 20) As String

or, a 3-dimensional array of Integer variables:

 Dim threeDIntArray(10, 10, 10) As Integer

The following program demonstrates creating and using a 2-dimensional array:

Module arrayApl

Sub Main()

' an array with 5 rows and 2 columns

Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6},{4, 8}}
Dim i, j As Integer
' output each array element's value '
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8

Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the
program. You can declare a dynamic array using the ReDim statement.

Syntax for ReDim statement:

ReDim [Preserve] arrayname(subscripts)

Where,

 The Preserve keyword helps to preserve the data in an existing array, when you resize it.
 arrayname is the name of the array to re-dimension.
 subscripts specifies the new dimension.

Example:
Module arrayApl
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
ReDim Preserve marks(10)
marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75
Console.WriteLine(“Index” & vbTab & “marks”)
For i = 0 To 10
Console.WriteLine(i & vbTab & marks(i))
Next i
Console.ReadKey()
End Sub
End Module

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

Index marks

0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0
CONTROL STATEMENTS:

 If Then Statement
 If Then Else Statement
 Nested If Then Else Statement
 Select Case Statement
1. If Then Statement
If Then statement is a control structure which executes a set of code only when the given
condition is true.
Syntax:
If [Condition] Then
[Statements]
End If

In the above syntax when the Condition is true then the Statements after Then are executed.

Example:
Private Sub Button1_Click_1(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
If Val(TextBox1.Text) > 25 Then
TextBox2.Text = "Eligible"
End If
Description:

In the above If Then example the button click event is used to check if the age got using TextBox1
is greater than 25, if true a message is displayed in TextBox2.

2. If Then Else Statement


If Then Else statement is a control structure which executes different set of code statements
when the given condition is true or false.
Syntax:
If [Condition] Then
[Statements]
Else
[Statements]
End If
In the above syntax when the Condition is true, the Statements after Then are executed.If the
condition is false then the statements after the Else part is executed.

Example:
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
If Val(TextBox1.Text) >= 40 Then
MsgBox("GRADUATED")
Else
MsgBox("NOT GRADUATED")
End If
End Sub
3. Nested If Then Else Statement
Nested If..Then..Else statement is used to check multiple conditions using if then else
statements nested inside one another.
Syntax:
If [Condition] Then
ElseIf [Condition] Then
[Statements]
ElseIf [Condition] Then
[Statements]
Else
[Statements]
End If

In the above syntax when the Condition of the first if then else is true, the second if then else is
executed to check another two conditions. If false the statements under the Else part of the first
statement is executed.

Example:

Private Sub Button1_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles Button1.Click
If Val(TextBox1.Text) >= 40 Then
Else If Val(TextBox1.Text) >= 60 Then
MsgBox("You have FIRST Class")
Else
MsgBox("You have SECOND Class")
Else
MsgBox("Check your Average marks entered")
End If
End Sub
4. Select Case Statement
Select case statement is used when the expected results for a condition can be known
previously so that different set of operations can be done based on each condition.
Syntax:
Select Case Expression
Case Expression1
Statement1
Case Expression2
Statement2
Case Expressionn
Statement n
...
Case Else
Statement
End Select

In the above syntax, the value of the Expression is checked with Expression1..n to check if the
condition is true. If none of the conditions are matched the statements under the Case Else is
executed.

Example:
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim c As String
c = TextBox1.Text
Select c
Case "Red"
MsgBox("Color code of Red is::#FF0000")
Case "Green"
MsgBox("Color code of Green is::#808000")
Case "Blue"
MsgBox("Color code of Blue is:: #0000FF")
Case Else
MsgBox("Enter correct choice")
End Select
End Sub

LOOPING STATEMENT
 While End while
 Do While Loop Statement
 Do Loop While Statement
 Do Loop Until Statement
 For Next Loop Statement

1. While End while Statement


While end while Statement is a looping statement where a condition is checked first, if it is
true a set of statements are executed. The condition can also become false atleast once while this
statement is used.
Syntax:
While condition
[statements]
End while
In the above syntax the Statements are executed when the Condition is true. The condition
may also become false while the statements are executed.
Example:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim n As Integer
n = 1
While n <= 1
n = n + 1
MsgBox("First incremented value is:" & n)
End While
End Sub
Description:
In the above example, the value of n is 2 in the loop, which is false according to the
condition but the loop is continued until the condition is checked. Thus the while wend
statement can be used.
2. Do While Loop Statement
Do While Loop Statement is used to execute a set of statements only if the condition is
satisfied. But the loop get executed once for a false condition once before exiting the loop. This
is also know as Entry Controlled loop.
Syntax:
Do While [Condition]
[Statements]
Loop
In the above syntax the Statements are executed till the Condition remains true.
Example:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim a As Integer
a = 1
Do While a < 100
a = a * 2
MsgBox("Product is::" & a)
Loop
End Sub
Description:

In the above Do While Loop example the loop is continued after the value 64 to display 128 which
is false according to the given condition and then the loop exits.

3. Do Loop While Statement


Do Loop While Statement executes a set of statements and checks the condition, this is
repeated until the condition is true. .It is also known as an Exit Control loop
Syntax:
Do
[Statements]
Loop While [Condition]

In the above syntax the Statements are executed first then the Condition is checked to find if it is
true.

Example:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim cnt As Integer
Do
cnt = 10
MsgBox("Value of cnt is::" & cnt)
Loop While cnt <= 9
End Sub
Description:

In the above Do Loop While example, a message is displayed with a value 10 only after which the
condition is checked, since it is not satisfied the loop exits.

4. Do Loop Until Statement


Do Loop Until Statement executes a set of statements until a condition becomes false, this is
an infinite loop might have to terminated using Ctrl + Break .
Syntax:
Do
[Statements]
Loop Until [Condition]

In the above syntax the Statements are executed until the Condition becomes false.

Example:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim X As String
Do
X$ = InputBox$("Correct Password Please")
Loop Until X$ = "Ranger"
End Sub
Description:

In the above Do Until Loop example, a input box is displayed until the correct password is typed.

5. For Next Loop Statement

For Next Loop Statement executes a set of statements repeatedly in a loop for the given
initial, final value range with the specified step by step increment or decrement value.
Syntax:
For counter = start To end [Step]
[Statement]
Next [counter]

In the above syntax the Counter is range of values specified using the Start ,End parameters. The
Step specifies step increment or decrement value of the counter for which the statements are
executed.
Example:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer
Dim j As Integer
j = 0
For i = 1 To 10 Step 1
j = j + 1
MsgBox("Value of j is::" & j)
Next i
End Sub
Description:

In the above For Next Loop example the counter value of i is set to be in the range of 1 to 10 and is
incremented by 1. The value of j is increased by 1 for 10 times as the loop is repeated.
UNIT-II
PROCEDURES
 Procedures are also used for implementing repeated tasks, such as frequently used
calculations.
 The two types of procedures supported by Visual Basic .NET. They are
 Subroutines or Procedure
 functions
Modular Coding
 The idea of breaking a large application into smaller, more manageable sections is not new
to computing.
 Few tasks, programming or otherwise, can be managed as a whole.
 The event handlers are just one example of breaking a large application into smaller tasks.
Some event handlers may required a lot of code.

 You could calculate the net profit with the following statements, which will most likely
appear
behind a button’s event handler:
RetrievePOLines(productID)
Sum1 = SumQtyPrice()
Qty1 = SumQuantities()
RetrieveInvoiceLines(productID)
Sum2 = SumQtyPrice()
Net = (Sum2 – Sum1) / Qty1
 The task is broken into smaller units, and each unit is implemented by a function or
subroutine.
 The name of the procedure indicates the operationit performs. First, the RetrievePOLines()
subroutine retrieves quantities and purchase prices ofa specific product—the productID
argument—from a database. The SumQtyPrice() function multiplies the quantities by prices
at which they were sold and sums the results to get the total value paid for the purchase of a
specific product. This result is stored in the Sum1 variable. The SumQuantities() function
sums the unit quantities into the Qty1 variable.
Subroutines/Procedure
 A subroutine is a block of statements that carries out a well-defined task.
 Subroutine or procedure does not return any values.
 A procedure is a group of statements that together perform a task when called.

 The block of statements is placed within a set of Sub…End Sub statements and can be
invoked by name.
Syntax:

[Modifiers] Sub SubName [(ParameterList)]


[Statements]
End Sub

Example:
Module Module1

Sub SitDown()
MsgBox("This program expects that you are sitting down!")
End Sub

Sub Main()
SitDown()
End Sub
End Module

 All variables declared within a subroutine are local to that subroutine. When the subroutine
exits, all variables declared in it cease to exist.

Procedure Program:-

Imports System.Console
Module Module1
Sub square(ByVal a As Integer)
Console.WriteLine("The Area of square is:" & (a * a))
End Sub
Sub rectangle(ByVal l As Integer, ByVal w As Integer)
Console.WriteLine("The Area of Rectangle is:" & (l * w))
End Sub
Sub circle(ByVal r As Integer)
Console.WriteLine("The Area of Circle is:" & (3.14 * r * r))
End Sub
Sub triangle(ByVal b As Integer, ByVal h As Integer)
Console.WriteLine("The Area of Triangle is:" & ((b * h) / 2))
End Sub

Sub Main()
Dim a, l, w, b, h, r As Integer
Console.WriteLine("")
Console.WriteLine("Enter the A value:")
a = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Enter the L value:")
l = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Enter the W value:")
w = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Enter the B value:")
b = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Enter the H value:")
h = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Enter the R value:")
r = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Prodecure")
Console.WriteLine("")
square(a)
Console.WriteLine("")
rectangle(l, w)
Console.WriteLine("")
circle(r)
Console.WriteLine("")
triangle(b, h)
Console.WriteLine("")
End Sub
End Module

Functions
 A function is similar to a subroutine, but a function returns a result.

 Subroutines perform a task and don’t report anything to the calling program; functions
commonly carry out calculations and report the result. Because they return values,
functions—like variables—have types.

Defining a Function
The Function statement is used to declare the name, parameter and the body of a function. The
syntax for the Function statement is:

[Modifiers] Function FunctionName [(ParameterList)] As ReturnType


[Statements]
End Function

Where,

 Modifiers: specify the access level of the function; possible values are: Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and
shadowing.
 FunctionName: indicates the name of the function
 ParameterList: specifies the list of the parameters
 ReturnType: specifies the data type of the variable the function returns

 The value you pass back to the calling program from a function is called the return value,
and its type must match the type of the function. Functions accept arguments, just like
subroutines.
 The statements that make up a function are placed in a set of Function…End Function
statements, as shown here:
Function NextDay() As Date
Dim theNextDay As Date
theNextDay = DateAdd(DateInterval.Day, 1, Now())
Return(theNextDay)
End Function
DateAdd() is a built-in function that adds a number of intervals to a date.

Calling Functions and Subroutines

 When you call a procedure, you must supply values for all the arguments specified in the
procedure’s definition and in the same order.
 To call a procedure, you simply enter its name, followed by its arguments in parentheses:

Dim chDigit As String


chDigit = ISBNCheckDigit(“078212283”)

 The values of the arguments must match their declared type. If a procedure expects an
integer value, you shouldn’t supply a date value or a string.
 If the procedure is a function, you must assign its return value to a variable so you can use it
from within your code.
 The following statement creates the complete ISBN by calling the ISBNCheckDigit()
function:

Dim ISBN As String = “078212283”


MsgBox(“The complete ISBN is “ & ISBN & ISBNCheckDigit(ISBN))

 The argument of the MsgBox() function needs a some explanation. It calls the ISBNCheck-
Digit() function, passing the ISBN as argument. Then it appends the check digit (which is the value
returned by the function) to the ISBN value and prints it. It is equivalent to the following statements,
which are simpler to read, but not nearly as common:

Dim wholeISBN As String


wholeISBN = ISBN & ISBNCheckDigit(ISBN)
MsgBox(“The complete ISBN is “ & wholeISBN)

Functions are called by name, and a list of arguments follows the name in parentheses as shown:

Degrees = Fahrenheit(Temperature)

In this example, the Fahrenheit() function converts the Temperature argument (which presumably is
the temperature in degrees Celsius) to degrees Fahrenheit, and the result is assigned to the Degrees
Variable.

ARGUMENTS

 Subroutines and functions aren’t entirely isolated from the rest of the application.
 Most procedures accept arguments from the calling program.
 Recall that an argument is a value you pass to the procedure and on which the procedure
usually acts.
 Functions also accept arguments—in many cases, more than one.
 The function Min(), for instance, accepts two numbers and returns the smaller one:

Function Min(ByVal a As Single, ByVal b As Single) As Single


Min = IIf(a < b, a, b)
End Function
Argument-Passing Mechanisms

 One of the most important issues in writing procedures is the mechanism used to pass
arguments.

 The examples so far have used the default mechanism: passing arguments by value.

 The other mechanism is passing them by reference.

Passing Arguments by Value


 When you pass an argument by value, the procedure sees only a copy of the argument.
 Even if the procedure changes it, the changes aren’t permanent.
 The benefit of passing arguments by value is that the argument values are isolated from the
procedure, and only the code segment in which they are declared can change their values.
This is the default argument-passing mechanism in VB.NET.
 To specify the arguments that will be passed by value, use the ByVal keyword in front of
the argument’s name.
Example
Module Module1
Function cube(ByVal a As Integer)
Return a * a * a

End Function
Function cylinder(ByVal r As Integer, ByVal h As Integer)
Return 3.14 * r * r * h
End Function
Function cone(ByVal r As Integer, ByVal h As Integer)
Return 1 / 3 * 3.14 * r * r * h
End Function
Function sphere(ByVal r As Integer)
Return 4 / 3 * 3.14 * r * r * r
End Function

Sub Main()
Dim a As Integer
Dim r, h As Integer
Console.WriteLine("Enter the a value:")
Console.WriteLine("")
a = Console.ReadLine()
Console.WriteLine("Enter the r value:")
Console.WriteLine("")
r = Console.ReadLine()
Console.WriteLine("Enter the h value:")
Console.WriteLine("")
h = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Functions:-")
Console.WriteLine("")
Console.WriteLine("The Volume Of Cube:" & cube(a))
Console.WriteLine("")
Console.WriteLine("The Volume Of Cylinder:" & cylinder(r, h))
Console.WriteLine("")
Console.WriteLine("The Volume Of Cone:" & cone(r, h))
Console.WriteLine("")
Console.WriteLine("The Volume Of Sphere:" & sphere(r))
Console.WriteLine("")
End Sub
End Module
Passing Arguments by Reference

 Passing arguments by reference gives the procedure access to the actual variable.

 The calling procedure passes the address of the variable in memory so that the procedure can
change its value permanently.

 Start a new Visual Basic project and enter the following function definition in the form’s
code
window:

Function Add(ByRef num1 As Integer, ByRef num2 As Integer) As Integer


Add = num1 + num2
num1 = 0
num2 = 0
End Function

This simple function adds two numbers and then sets them to zero.

Next, place a Command button on the form and enter the following code in the button’s Click event:

Dim A As Integer, B As Integer


A = 10
B=2
Dim Sum As Integer
Sum = Add(A, B)
Console.WriteLine(A)
Console.WriteLine(B)
Console.WriteLine(Sum)

This code displays the following results in the Output window:


0
0
12
Structures
 Structures can be defined as a tool for handling a group of logically related data items.
 Structures is defined as a collection of heterogeneous data element that can be stored under a
common variable name.
 They are user-defined and provide a method for packing together data of different types.
 Structures are very similar to Classes.
 The main difference between classes and structures is, classes are reference types and structures
are value types.
 The structure in VB.NET can contain fields, methods, constants, constructors, properties,
indexers, operators and even other structure types.

Structure Declaration & Object Creation.

 The keyword struct can be used to declare a structure. The general form of a structure
declaration in VB.NET is as follows.

Syntax:

[Modifiers] Structure struct_name


Dim variable_1 as type_1
Dim variable_2 as type_2
……
Dim variable_n as type_n
End Structure

Where the modifier can be private, public, internal or public. The structure is the required keyword.

For example

Structure MyStruct
Public x As Integer
Public y As Integer
End Structure 'MyStruct

 The objects of a strcut can be created by using the new operator as follows.
Dim ms As New MyStruct()
 The individual members of a struct can be accessed by using the dot (.) operator as showing
below.
ms.x = 10
ms.y = 20
 Remember that unlike classes, the strcut object can also be created without using the new
operator.
Dim ms As MyStruct
 A struct in VB.NET can contain fields. These fields can be declared as private, public, internal.
Remember that inside a struct, we can only declare a field. We can't initialize a field inside a
struct. However we can use constructor to initialize the structure fields.
 The following is not a valid VB.NET struct and the code will not compile, since the fields inside
the structure are trying to initialize.
Structure MyStruct
Private x As Integer = 20
Private y As Integer = 20
End Structure 'MyStruct

Structures Vs Classes

Structures Classes
Value type Reference type
Supports data members, code members Supports data members, code members
(methods) and events (methods) and events
Can not inherit Supports inheritance

Preferable when you perform large number Preferable when you need to initialize
of operations on each instance one or more members upon creation

Can not control initialization


Can have parameterized constructors
usingstructure variable
More flexible, unlimited event
Less flexible, limited event handling support
handling support
Code for creating a structure
The following code creates a structure named Employee with five fields of different data types.
Module Module1
Structure Employee
'declaring a structure named Employee
Dim EmpName As String
Dim EmpDesignation As String
Dim EmpCity As String
Dim EmpSal As Double
Dim EmpId As Integer
'declaring five fields of different data types in the structure
End Structure

Sub Main()
Dim san As New Employee()
'creating an instance of Employee
san.EmpName = "Sandeep"
san.EmpDesignation = "Software Developer"
san.EmpCity = "Sydney"
san.EmpSal = 60000
san.EmpId = 2707
'assigning values to member variables
WriteLine("EmpName" + " " + san.EmpName)
WriteLine("EmpDesignation" + " " + san.EmpDesignation)
WriteLine("EmpCity" + " " + san.EmpCity)
WriteLine("EmpSalary" + " " + san.EmpSal.ToString)
WriteLine("EmpID" + " " + san.EmpId.ToString)
'accessing member variables with the period/dot operator
Read()
End Sub
End Module
The output of above code is the image below.

Collections and Lists


 Collection will be in the system. Collection Namespace.

 Collection classes are specialized classes for data storage and retrieval.

 These classes provide support for stack, queue, list and hash table.

Array List
 Array List is one of the most flexible data structure from VB.NET Collections.

 ArrayList contains a simple list of values and very easily we can add, insert , delete , view
etc. to do with ArrayList.

 It is very flexible because we can add without any size information that is it grow
dynamically and also shrink.

 It represent ordered collection of an object that can be indexed individually.

 Unlike array you can add and remove items from a list at a specified position using an index
and resize the array itself automatically.

 It also allow dynamic memory allocation add, search, and sort items in the list.

Properties and Methods of the Array List Class


The following table lists some of the commonly used properties of the ArrayList class:

Property Description
Capacity Gets or sets the number of elements that the ArrayList can contain.
Count Gets the number of elements actually contained in the ArrayList.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.
IsReadOnly Gets a value indicating whether the ArrayList is read-only.
Item Gets or sets the element at the specified index.
The following table lists some of the commonly used methods of the ArrayList class:

Important Methods in array list:-

 Add() : Add an Item in an ArrayList


 Insert (): Insert an Item in a specified position in an ArrayList
 Remove (): Remove an Item from ArrayList
 RemoveAt(): remeove an item from a specified position
 Sort (): Sort Items in an ArrayList
 Reverse(): Reverse the order of element in the Array List
 Contains() : Determine whether an element is in the array list.

How to add an Item in an ArrayList ?

Syntax : ArrayList.add(Item)

Item : The Item to be add the ArrayList

Dim ItemList As New ArrayList()

ItemList.Add("Item4")

How to Insert an Item in an ArrayList ?

Syntax : ArrayList.insert(index,item)

index : The position of the item in an ArrayList

Item : The Item to be add the ArrayList

ItemList.Insert(3, "item6")

How to remove an item from arrayList ?

Syntax : ArrayList.Remove(item)

Item : The Item to be add the ArrayList

ItemList.Remove("item2")

How to remove an item in a specified position from an ArrayList ?

Syntax : ArrayList.RemoveAt(index)

index : the position of an item to remove from an ArrayList

ItemList.RemoveAt(2)

How to sort ArrayList ?

Syntax : ArrayListSort()
The following VB.NET source code shows some function in ArrayList

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim ItemList As New ArrayList()
ItemList.Add("Item4")
ItemList.Add("Item5")
ItemList.Add("Item2")
ItemList.Add("Item1")
ItemList.Add("Item3")
MsgBox("Shows Added Items")
For i = 0 To ItemList.Count - 1
MsgBox(ItemList.Item(i))
Next
'insert an item
ItemList.Insert(3, "Item6")
'sort itemms in an arraylist
ItemList.Sort()
'remove an item
ItemList.Remove("Item1")
'remove item from a specified index
ItemList.RemoveAt(3)
MsgBox("Shows final Items the ArrayList")
For i = 0 To ItemList.Count - 1
MsgBox(ItemList.Item(i))
Next
End Sub
End Class
When you execute this program , at first add five items in the arraylist and displays. Then
again one more item inserted in the third position , and then sort all items. Next it remove the item1
and also remove the item in the third position . Finally it shows the existing items.

Example 2:

The following example demonstrates the concept:

Sub Main()
Dim al As ArrayList = New ArrayList()
Dim i As Integer
Console.WriteLine("Adding some numbers:")
al.Add(45)
al.Add(78)
al.Add(33)
al.Add(56)
al.Add(12)
al.Add(23)
al.Add(9)
Console.WriteLine("Capacity: {0} ", al.Capacity)
Console.WriteLine("Count: {0}", al.Count)
Console.Write("Content: ")
For Each i In al
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.Write("Sorted Content: ")
al.Sort()
For Each i In al
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.ReadKey()
End Sub
End Module

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

Adding some numbers:


Capacity: 8
Count: 7
Content: 45 78 33 56 12 23 9
Content: 9 12 23 33 45 56 78

Hash Table:-
The Hashtable class represents a collection of key-and-value pairs that are organized based
on the hash code of the key. It uses the key to access the elements in the collection.

A hashtable is used when you need to access elements by using key, and you can identify a
useful key value. Each item in the hashtable has a key/value pair. The key is used to access the items
in the collection.

Properties and Methods of the Hashtable Class

The following table lists some of the commonly used properties of the Hashtable class:

Property Description
Count Gets the number of key-and-value pairs contained in the Hashtable.
IsFixedSize Gets a value indicating whether the Hashtable has a fixed size.
IsReadOnly Gets a value indicating whether the Hashtable is read-only.
Item Gets or sets the value associated with the specified key.
Keys Gets an ICollection containing the keys in the Hashtable.
Values Gets an ICollection containing the values in the Hashtable.

The following table lists some of the commonly used methods of the Hashtable class:

Add : To add a pair of value in HashTable

Syntax : HashTable.Add(Key,Value)

Key : The Key value

Value : The value of corrosponding key

ContainsKey : Check if a specified key exist or not

Synatx : HashTable.ContainsKey(key)
Key : The Key value for search in HahTable

ContainsValue : Check the specified Value exist in HashTable

Synatx : HashTable.ContainsValue(Value)

Value : Search the specified Value in HashTable

Remove : Remove the specified Key and corrosponding Value

Syntax : HashTable.Remove(Key)

Key : The argument key of deleting pairs

The following source code shows all important operations in a HashTable

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim weeks As New Hashtable
Dim day As DictionaryEntry
weeks.Add("1", "Sun")
weeks.Add("2", "Mon")
weeks.Add("3", "Tue")
weeks.Add("4", "Wed")
weeks.Add("5", "Thu")
weeks.Add("6", "Fri")
weeks.Add("7", "Sat")
'Display a single Item
MsgBox(weeks.Item("5"))
'Search an Item
If weeks.ContainsValue("Tue") Then
MsgBox("Find")
Else
MsgBox("Not find")
End If
'remove an Item
weeks.Remove("3")
'Display all key value pairs
For Each day In weeks
MsgBox(day.Key " -- " day.Value)
Next
End Sub
End Class

When you execute this program it add seven weekdays in the hash table and display the
item 5. Then it check the item "Tue" is existing or not . Next it remove the third item from Hash
Table. Finally it displays all item exist in the Hash Table.

Example:

The following example demonstrates the concept:


Module collections
Sub Main()
Dim ht As Hashtable = New Hashtable()
Dim k As String
ht.Add("001", "Zara Ali")
ht.Add("002", "Abida Rehman")
ht.Add("003", "Joe Holzner")
ht.Add("004", "Mausam Benazir Nur")
ht.Add("005", "M. Amlan")
ht.Add("006", "M. Arif")
ht.Add("007", "Ritesh Saikia")
If (ht.ContainsValue("Nuha Ali")) Then
Console.WriteLine("This student name is already in the list")
Else
ht.Add("008", "Nuha Ali")
End If
' Get a collection of the keys.
Dim key As ICollection = ht.Keys
For Each k In key
Console.WriteLine(" {0} : {1}", k, ht(k))
Next k
Console.ReadKey()
End Sub
End Module

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

006: M. Arif
007: Ritesh Saikia
008: Nuha Ali
003: Joe Holzner
002: Abida Rehman
004: Mausam Banazir Nur
001: Zara Ali
005: M. Amlan

Sorted List

 The SortedList class represents a collection of key-and-value pairs that are sorted by the keys
and are accessible by key and by index.
 A sorted list is a combination of an array and a hashtable.
 It contains a list of items that can be accessed using a key or an index.
 If you access items using an index, it is an ArrayList, and if you access items using a key, it
is a Hashtable.
 The collection of items is always sorted by the key value.

Properties and Methods of the Sorted List Class

The following table lists some of the commonly used properties of the SortedList class:

Property Description
Capacity Gets or sets the capacity of the SortedList.
Count Gets the number of elements contained in the SortedList.
IsFixedSize Gets a value indicating whether the SortedList has a fixed size.
IsReadOnly Gets a value indicating whether the SortedList is read-only.
Item Gets and sets the value associated with a specific key in the SortedList.
Keys Gets the keys in the SortedList.
Values Gets the values in the SortedList.

The following table lists some of the commonly used methods of the SortedList class:

S.No Method Name & Purpose


Public Overridable Sub Add ( key As Object, value As Object )
1
Adds an element with the specified key and value into the SortedList.
Public Overridable Sub Clear
2
Removes all elements from the SortedList.
Public Overridable Function ContainsKey ( key As Object ) As Boolean
3
Determines whether the SortedList contains a specific key.
Public Overridable Function ContainsValue ( value As Object ) As Boolean
4
Determines whether the SortedList contains a specific value.
Public Overridable Function GetByIndex ( index As Integer ) As Object
5
Gets the value at the specified index of the SortedList.
Public Overridable Function GetKey ( index As Integer ) As Object
6
Gets the key at the specified index of the SortedList.
Public Overridable Function GetKeyList As IList
7
Gets the keys in the SortedList.
Public Overridable Function GetValueList As IList
8
Gets the values in the SortedList.
Public Overridable Function IndexOfKey ( key As Object ) As Integer
9
Returns the zero-based index of the specified key in the SortedList.
Public Overridable Function IndexOfValue ( value As Object ) As Integer
10
Returns the zero-based index of the first occurrence of the specified value in the SortedList.
Public Overridable Sub Remove ( key As Object )
11
Removes the element with the specified key from the SortedList.
Public Overridable Sub RemoveAt ( index As Integer )
12
Removes the element at the specified index of SortedList.
Public Overridable Sub TrimToSize
13
Sets the capacity to the actual number of elements in the SortedList.

Example:

The following example demonstrates the concept:

Module collections
Sub Main()
Dim sl As SortedList = New SortedList()
sl.Add("001", "Zara Ali")
sl.Add("002", "Abida Rehman")
sl.Add("003", "Joe Holzner")
sl.Add("004", "Mausam Benazir Nur")
sl.Add("005", "M. Amlan")
sl.Add("006", "M. Arif")
sl.Add("007", "Ritesh Saikia")
If (sl.ContainsValue("Nuha Ali")) Then
Console.WriteLine("This student name is already in the list")
Else
sl.Add("008", "Nuha Ali")
End If
' Get a collection of the keys.
Dim key As ICollection = sl.Keys
Dim k As String
For Each k In key
Console.WriteLine(" {0} : {1}", k, sl(k))
Next k
Console.ReadKey()
End Sub
End Module

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

001: Zara Ali


002: Abida Rehman
003: Joe Holzner
004: Mausam Banazir Nur
005: M. Amlan
006: M. Arif
007: Ritesh Saikia
008: Nuha Ali

VB.Net - Classes & Objects

When you define a class, you define a blueprint for a data type. This doesn't actually define any
data, but it does define what the class name means, that is, what an object of the class will consist of
and what operations can be performed on such an object.

Objects are instances of a class. The methods and variables that constitute a class are called
members of the class.

Class Definition

A class definition starts with the keyword Class followed by the class name; and the class body,
ended by the End Class statement. Following is the general form of a class definition:

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit |


NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class

Where,

 attributelist is a list of attributes that apply to the class. Optional.


 accessmodifier defines the access levels of the class, it has values as - Public, Protected,
Friend, Protected Friend and Private. Optional.
 Shadows indicate that the variable re-declares and hides an identically named element, or set
of overloaded elements, in a base class. Optional.
 MustInherit specifies that the class can be used only as a base class and that you cannot
create an object directly from it, i.e., an abstract class. Optional.
 NotInheritable specifies that the class cannot be used as a base class.
 Partial indicates a partial definition of the class.
 Inherits specifies the base class it is inheriting from.
 Implements specifies the interfaces the class is inheriting from.

The following example demonstrates a Box class, with three data members, length, breadth and
height:

Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
' box 1 specification
Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0
' box 2 specification
Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0
'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module

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

Volume of Box1 : 210


Volume of Box2 : 1560

Building Windows Applications


In Visual Basic (any version), a window is known as a form. With the .NET Framework, this form
design capability has been brought to all of the managed languages as Windows Forms.
In particular, you will look at:
 Adding more features using buttons, text boxes, and radio buttons
 Creating a simple toolbar and toolbar buttons to respond to events
Creating additional forms in a Windows Forms application
Using Button Events

From the Toolbox, drag a Button control onto the form. Change its Text property to Hello, world!
and its Name property to btnSayHello. Resize your button so that it looks similar to the one shown
below:
Private Sub btnSayHello_Click(ByVal sender As System.Object, _ ByVal e As
System.EventArgs) Handles btnSayHello.Click
‘Display a MessageBox
MessageBox.Show(“Hello, world!”, Me.Text)
End Sub

Building a Simple Application


Building the Form

The first job is to start a new project and build a form. This form will contain a multiline text
box where you can enter text. It will also contain two radio buttons that will give you the option of
counting either the words or the number of characters in the text box.

Exercise - Building the Form

1. Select File New Project from the Visual Studio 2005 menu and create a new Windows
Application project. Enter a project name of Word Counter and click OK.

2. Click on Form1 and, in the Properties window, set the Size property to 424, 312, the StartPosition
property to CenterScreen, and the Text property to Word Counter.

3. Drag a TextBox control from the Toolbox and drop it on the form. Now change the properties of
the text box as shown in the following list:

 Set Name to txtWords.


 Set Location to 8, 32.
 Set Multiline to True.
 Set ScrollBars to Vertical.
 Set Size to 400, 217.

4. To tell the user what to do with the form, you add a label. Select the Label control from the
Toolbox, drag and drop it just above the text box. Change the Text property to Enter some text into
this box.

Strictly speaking, unless you’re going to need to talk to the control from your code, you don’t need
to change its Name property. With the text box, you need to use its properties and methods to make
the application work. However, the label is just there for esthetics, so you don’t need to change the
name for Label1.

5. Your application is going to be capable of counting either the characters the user entered or the
number of words. To allow the user to select the preferred count, you use two radio buttons. Draw
two RadioButton controls onto the form next to each other below the text box. You need to refer to
the radio buttons from your Visual Basic .NET code, so change the properties as shown in the
following lists:

For the first radio button:

 Set Name to radCountChars.


 Set Checked to True.
 Set Text to Chars.
For the second radio button:

 Set Name to radCountWords.


 Set Text to Words.

6. As the user types, you’ll take the characters that the user enters and count up the words or
characters as appropriate. You want to pass your results to the user, so add two new Label controls
next to the RadioButton controls that you just added.

7. The first Label control (marked Label2) is just for esthetics, so change its Text property to The
results are:. The second Label control will report the results, so you need to give it a name. Set the
Name property as lblResults and clear the Text property.

8. You also need a Button control that will show a message box, so add a Button control to the form
and align it to the bottom right of the text box. You don’t strictly need this because the user can read
the results on the form, but it will illustrate a couple of important points. Change the Name property
to btnShowMe and the Text property to Show Me!. Your completed form should look similar to the
one shown here:

9. Now that you have the controls laid out on your form the way you want it, you can make sure you
keep it that way. Make sure you select one of the controls and not the actual form, and then select
Format Lock Controls from the menu. This sets the Locked property of each of the controls to
True and prevents them from accidentally being moved, resized, or deleted.

Displaying Dialog Boxes

 Visual Basic .NET provides several built-in dialog boxes that help you provide a rich user
interface in your front-end applications.
 These dialog boxes provide the same common user interface that is found in most Windows
applications.
 They also provide many properties and methods that allow you to customize these dialog
boxes to suit your needs while still maintaining the standard look of Windows applications.

Using MessageBox
 In the day-to-day operation of a computer, you have seen message boxes that display
one of the icons shown in below figure.

 The first icon this figure has three names: Error, Hand, and Stop.
 The second icon has only one name: Question.
 The third icon has two names: Exclamation and Warning.
 The final icon has two names: Asterisk and Information.

Available Icons
Member Name Description
Asterisk Specifies that the message box displays an information icon
Information Specifies that the message box displays an information icon
Error Specifies that the message box displays an error icon
Hand Specifies that the message box displays an error icon
Stop Specifies that the message box displays an error icon
Exclamation Specifies that the message box displays an exclamation icon
Warning Specifies that the message box displays an exclamation icon
Question Specifies that the message box displays an exclamation icon
None Specifies the message box will not display any icon

Available Buttons
Member Name Description
AbortRetryIgnore Specifies that the message box displays Abort, Retry, and Ignore
buttons
OK Specifies that the message box displays an OK button
OKCancel Specifies that the message box displays OK and Cancel buttons
RetryCancel Specifies that the message box displays Retry and Cancel buttons
YesNo Specifies that the message box displays Yes and No buttons
YesNoCancel Specifies that the message box displays Yes, No, and Cancel buttons

Default Buttons
Member Name Description
Button1 Specifies that the first button in the message box should be the default
button
Button2 Specifies that the second button in the message box should be the
default button
Button3 Specifies that the third button in the message box should be the
default button
Show Method Syntax
You call the Show method to display the message box.

MessageBox.Show("My Text", "My Caption", MessageBoxButtons.OKCancel, _


MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)

The More common syntax for MessageBox.Show method

 MessageBox.Show(message text)
 MessageBox.Show(message text, caption)
 MessageBox.Show(message text, caption, buttons)
 MessageBox.Show(message text, caption, buttons, icon)
 MessageBox.Show(message text, caption, buttons, icon, default button)

The following table shows the available members in the DialogResult enumeration.

Member Name Description


Abort The return value is Abort and is the result of clicking the Abort button
Cancel The return value is Cancel and is the result of clicking the Cancel button
Ignore The return value is Ignore and is the result of clicking the Ignore button
No The return value is No and is the result of clicking the No button
None Nothing is returned, which means the dialog box continues running until a
button is clicked
OK The return value is OK and is the result of clicking the OK button
Retry The return value is Retry and is the result of clicking the Retry button
Yes The return value is Yes and is the result of clicking the Yes button

WORKING WITH FORMS


In Visual Basic, the form is the container for all the controls that make up the user
interface.
When a Visual Basic application is executing, each window it displays on the desktop is a form.

You can move a form around, resize it, and even cover it with other forms. You do with the
mouse, or with the keyboard through the Control menu.

they are “intelligent” objects that are aware of the controls placed on them and can actually
manipulate the controls at runtime

The Appearance of Forms


Applications are made up of one or more forms (usually more than one), and the forms are what
users see.

The elements of the form

Clicking the icon on the left end of the title bar opens the Control menu, which contains the
Commands. On the right end of the title bar are three buttons: Minimize, Maximize, and Close.

Clicking these buttons performs the associated function. When a form is maximized, the
maximize button is replaced by the Restore button. When clicked, this button resets the form to the
size and position before it was maximized.
The Restore button is then replaced by the Maximize button.
Command Effect
Restore Restores a maximized form to the size it was before it was maximized; available only if
the form has been maximized
Move Lets the user move the form around with the mouse
Size Lets the user resize the form with the mouse
Minimize Minimizes the form
Maximize Maximizes the form
Close Closes the current form

Properties of the Form Control


The floating toolbars used by many graphics applications, for example, are actually forms
with a narrow title bar. The dialog boxes that display critical information or prompt you to select the
file to be opened are also forms. You can duplicate the look of any window or dialog box
through the following properties of the Form object.
Form Properties

Forms in Visual Basic.net 2008 is so important to the user as it is the application for the user. So
identifying and displaying forms is vital to the usability of an application. Even the developers need
to alter the properties to manage the forms in VB.net.

Following table lists some important Properties of Forms in Visual Basic.net 2008.

Properties Description
BackColor Set's the background color for the form
BackgroundImage Set's the background image for the form
Set the cursor image when it hovers over the
Cursor
form.
Specifies whether to accept the data dragged and
AllowDrop
dropped onto the form.
Font Get or sets the font used in the form
Locked Specifies whether the form is locked.
FormBorderStyle Get or set border style of a form
Text Provide the title for a Form Window
Determines whether the ControlBox is available
Control Box by clicking the icon on the upper left corner of the
window.
Specifies icon for the window on the upper left
Icon
corner.
Sets the type of mouse pointer to be displayed
MousePointer
when hovered over an specific area.
Get or sets the form button if the enter key is
AcceptButton
pressed.
Language Specifies the loaclized language.
Autoscroll Specifies whether to enable auto scrolling.
Specifies whether to display the maximize option
MaximizaBox
in the caption bar of the form.
Defines whether the form is a container of
IsMDIChild
Multiple Document Interface(MDI) child form.
Specifies whether to display the minimize option
MinimizeBox
in the caption bar of the form.

Loading and Showing Forms


You may wish to display a second form to prompt the user for data specific to an application.
You must explicitly load the second form, read the information entered by the user, and then close
the form. Or, you may wish to maintain two forms open at once and let the user switch between
them.
your application has two forms, named Form1 and Form2, and that Form1 is the project’s
startup form. To show Form2 when an action takes place on Form1, first declare a variable
that references Form2:

Dim frm As New Form2

This declaration must appear in Form1 and must be placed outside any procedure.
Form2 from within Form1, execute the following statement:

frm.Show
Show / Hide Forms
Form in Visual Basic.net 2008 are displayed and hidden using two different methods.To display
a form the Show() method is used and to hide a form Hide() method is used.

Show Method:

This method is used to display the form on top of all other windows even if it is loaded or not loaded
into the memory.

Syntax:
FormName.Show
or
FormName.Show(1,)
In the above syntax, the Show method can also have argument values 0 or 1 for Modeless or Modal
forms. By default this methods modeless or normal forms, but the modal forms more interactive.

Hide Method:

This method hides a form object from the screen, still with the object being loaded in the memory.

Syntax:
FormName.Hide
Example:
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles Button1.Click
DisplayForm.Show()

End Sub

Private Sub Button2_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles Button2.Click
DisplayForm.Hide()

End Sub
End Class
Description:

In the above example, two forms Form1, Form2 are used. An image is added to Form2 using the
the click event of Button1 and Button2 the form is shown or hidden. Thus you can show or hide the
forms.

Show Hide Forms


Forms in VB.net 2008 are loaded and unloaded using two different statements.To load a form the
Load statement is used and to unload a form Unload statement is used.

Load Method:

This method is used to load a form into the memory, but will not display the form.

Syntax:
Load FormName
UnLoad Method:

This statement is used to unload a form from the memory.

Syntax:
UnLoad FormName

The Form’s Events


The Form object triggers several events, the most important of them being Activate, Deactivate,
Closing, Resize, and Paint.

The Activate and Deactivate Events


When more than one form is displayed, the user can switch from one to the other with the mouse or
by pressing Alt+Tab. Each time a form is activated, the Activate event takes place. Likewise, when
a
form is activated, the previously active form receives the Deactivate event.

The Closing Event


This event is fired when the user closes the form by clicking its Close button. If the application must
terminate because Windows is shutting down, the same event will be fired as well.
The Resize Event
The Resize event is fired every time the user resizes the form with the mouse.
The Paint Event
This event takes place every time the form must be refreshed. When you switch to another form that
partially or totally overlaps the current form and then switch back to the first form, the Paint event
will be fired to notify your application that it must redraw the form. In this event’s handler, we insert
the code that draws on the form.
The PaintForm() subroutine, which redraws the gradient on the form, must be called from within the
Paint and Resize events.

Filling a form’s background with a gradient

The Startup Form


A typical application has more than a single form. When an application starts, the main form is
loaded.
You can control which form is initially loaded by setting the startup object in the Project Properties
Window.

In the Properties window, you can specify the form


that’s displayed when the application starts.
Designing Menus
Menus are one of the most common and characteristic elements of the Windows user interface.
The Menu Editor
Menus can be attached only to forms, and they are implemented through the MainMenu
control. The items that make up the menu are MenuItem objects.
The MainMenu control and MenuItem objects give you absolute control over the structure
and appearance of the menus of your application.
CREATING MENUS
 Start a new project.To your new form,use the toolbox to add a MenuStrip control:
 Double click the control to add one to your form.

 Examine the bottom of your screen,on the left.

 This is the control itself.If you click on this(it’s highlighted above) ,you’ll see that the
Properties box on the right changes.There are many properties for the control.

 The Menu item object is one at the top of the form.

 To start building your menu,click inside the area that says”Type here”Type the world file:

 Now press the enter key on your keyboard.your menu will look like this:

To create item on your File menu.click inside the Type Here box,Enter the world New,and press
the

 Enter key on your keyboard again.Your menu will then look like this:

 Add an “Open” and a “Save” item to your menu in the same way.
 It should look like this:

 The final item we’ll add our menu is an”Exit” item.But you can add a

 separator between the “Save” and “Exit”

 To add a separator,click inside the blue “Type here” Box.Instead of typing a letter,type the
minus character”-”(in between the “0” key and the”+/” on your key board)When you hit
your return key,you’ll see the separator appear:

 Click inside the “Type here” area,and an Exit(or Quit) item.Click back on your form,away
from the menu,to finish off.You should now have a file.

The IDE provides a visual tool for designing menus, and then you can program their Click
event
handlers. each item (command) in a menu is represented by a MenuItem object, you can control the
application’s menus from within your code by manipulating the properties of the MenuItem objects.
Double-click the MainMenu icon on the Toolbox. The MainMenu control will be added to
the
form, and a single menu command will appear on your form.
Its caption will be Type Here. If you don’t see the first menu item on the Form right away,
select the MainMenu control in the Components tray below the form. Do as the caption says; click it
and enter the first command’s caption,File As soon as you start typing, two more captions appear:
one on the same level (the second command of the form’s main menu, representing the second pull-
down menu) and another one below File (representing the first command on the File menu). Select
the item under File and enter the string New.
As soon as you start entering the caption of a menu or menu item, more items appear to the left and below the
current item.

Enter the remaining items of the File menu—Open, Save, and Exit—and then click
somewhere
on the form. All the temporary items (the ones with the Type Here caption) will disappear, and the
menu will be finalized on the form. At any point, you can add more items by right-clicking one of
the existing menu items and selecting Insert New.
Caption Name
File FileMenu
New FileNew
Open FileOpen
Save FileSave
Exit FileExit
Edit EditMenu
Copy EditCopy
Cut EditCut
Paste EditPaste.

The Form.Controls Collection


All the controls on a form are members of the Controls property, which is a collection. The
Controls collection exposes members for accessing and manipulating the
controls at runtime, and these members are:

Add method
Adds a new element to the Controls collection. In effect, it adds a new control on
the current form.
The Add method accepts a control as argument and adds it to the collection. Its syntax is:
Controls.Add(controlObj)
where controlObj is an instance of a control.

Remove method
Removes an element from the Controls collection.
It accepts as argument either the index of the control to be removed, or a reference to the
control to be removed (a variable of the Control type that represents one of the controls on the
form). The syntax of these two forms is:

Me.Controls.Remove(index)
Me.Controls.Remove(controlObj)

Count property
Returns the number of elements in the Controls collection. The number of
controls on the current form is given by the expression
Me.Controls.Count

All method
Returns all the controls on a form (or in a container control) as an array of the
System.WinForms.Control type.
You can iterate through the elements of this array with the usual methods exposed by the
Array class.

Clear method

Removes all the elements of the Controls array.


Unit: III

WORKING WITH CONTROLS

TEXTBOX CONTROL:
The Textbox control is mainly used to accept the text form keyboard during runtime.
Three important properties of this control are Name, Text, and Multiline
. The Name property’s value is used in program code. The Text property’s value appears
directly in the textbox.

When we place a TextBox control on the form, the default value of Name property is TextBox
1. The default value of Text property is also TextBox1.
The default value of Multiline property is False. By default, we can place only one line of tet inside
a textbox.
If we wish to place two or more lines inside a textbox, we have to set the Multiline property
to True. The properties of TextBox control are discussed in the following table.

LABEL CONTROL:
Label control is a simple and at the same time useful control.
This control is used to label various item on a form. Some important properties of this
control are Name, text, Location, Size, BackColor, ForeColor, Font and Enabled.
As in the case of TextBox control, Name property’s value is used in program code. The
property’s value appears directly in the label.
BUTTON CONTROL:
The Button control looks like a push button on a TV panel. This control is used for issuing
commends.
It is one of the most frequently used controls.
Some important properties of this control are Name, Text, and FlatStyle.
As usual, the Name property’s value is used in the program cod and the Text property’s
value appears directly on the button.

RADIOBUTTON CONTROL:
The Radio Button control looks and behaves very much like a button in old-fashioned car
radio.
Radio button were known as option-button in Visual Basic 6. We use this control in a
project when we expect the user to choose only one item among many available items.
Some important properties of the Radio Button control are Name, Text, and Checked.
As usual, the Name property’s value is used in the program code and the Text property’s
value appears to the fight of the radiobuton.
Two possible values of Checked property are True and False. When a radio button is
clicked, its Checked property will be set to True.

EXAMPLE PROGRAM

If Red. Checked Then


InfoLabel. Text = “U have selected Red Exterior”
End If
If Green. Checked Then
InfoLabel. Text = “U have selected Green Exterior”

End If
If Blue. Checked Then
InfoLabel. Text = “U have selected Blue Exterior”

End If
If White. Checked Then
InfoLabel. Text = “U have selected White Exterior”
End If

CHECKBOX CONTROL:
The Checkbox control represents a checkable entity on the form. We checkboxes in a project
when we expect the user to choose a set of items among many available items.
`Some important properties of this control are Name, Text, and Checked.
As usual, the Name property’s value is used in the program code and the Text property’s
value appears to the right of Checkbox.

GROUPBOX CONTROL:
The Group Box control was known as Frame control in Visual Basic6.
We use this control to group the related controls. Suppose that we place ten radio buttons
on a form. In such a case, we can select only one of these ten radio buttons.
On the other hand, if we place the first five radio buttons inside a group box and the
remaining five radio buttons inside another group box,
we shell select one radio button form the first group box and another radio button f rom the
second group box.

EXAMPLE
1. CREATE A NEW Windows application and name it GroupBox Demo. Now, the form will
open in the designer mode.
2. In this example, we will place a Button control GroupBox control, four RadioButton
control, and two Label control on the form. We will change the name and Text properties of
the Button, GroupBox, Label, and Radiobutton controls. We will change the properties as
show in the following table:
3. Double-Click the Display Button control in order to create the event-handling method for
the Click event of this control.
4. Now, the template for the event-handling method will appear in the usual manner. Add the
code show in boidface below in the event-handling method so that the desired text will
appear within a label when the DisplayButton control is clicked.

If Red. Checked Then


InfoLabel. Text = “U have selected Red Exterior”
End If
If Green. Checked Then
InfoLabel. Text = “U have selected Green Exterior”
End If
If Blue. Checked Then
InfoLabel. Text = “U have selected Blue Exterior”
End If
If White. Checked Then
InfoLabel. Text = “U have selected White Exterior”
End If

LISTBOX CONTROL;
We have so far discussed three button-centric controls, namely the Button control,
Checkbox control, and Radio Button control. We will now discuss three list-selection-centric
controls, namely the List Box control, the CheckedListBox control, and Combo Box control.
EX;
Private Sub DisplayButton_Click(ByVal sender As System. Object, ByVal e As System.
EventArgs) Handles DisplayButton.Click
If ComputerMakerList.SelectedItem <> Nothing Then
InfoLabel. Text = “ u have selected the company : “ “ & computerMakerList. SelectedItem
End If

THE COMMON DIALOG CONTROLS


To use any of the common dialog controls in your interface, just place the appropriate
control from the Dialog section of the Toolbox on your form and activate it from within your code
by calling the Show Dialog method.

You simply add them to the project by double-clicking their icons in the Toolbox;

A new icon appears in the components tray of the form, just below the Form Designer.

The common dialog controls in the Toolbox are the following:

 OpenFileDialog - Lets users select a file to open. It also allows the selection of multiple files
for applications that must process many files at once.
 SaveFileDialog - Lets users select or specify the path of a file in which the current document
will be saved.
 FolderBrowserDialog - Lets users select a folder (an operation that can't be performed with
the OpenFileDialog control).
 ColorDialog - Lets users select a color from a list of predefined colors or specify custom
colors.Use to apply the currently selected font to the text without closing the dialog box.

Using the Common Dialog Controls


To display any of the common dialog boxes from within your application

You must first add an instance of the appropriate control to your project.

Then you must set some basic properties of the control through the Properties window.
Most applications set the control's properties from within the code because common dialogs
interact closely with the application.

When you call the Color common dialog, for example, you should preselect a color from
within your application and make it the default selection on the control.

When prompting the user for the color of the text, the default selection should be the current
setting of the control's Fore Color property.

As soon as you call the Show Dialog method, the corresponding dialog box appears
onscreen, and the execution of the program is suspended until the box is closed.

Using the Open, Save, and Folder Browser dialog boxes, users can traverse the entire
structure of their drives and locate the desired filename or folder.

When the user clicks the Open or Save button, the dialog box closes and the program's
execution resumes.

The code should read the name of the file selected by the user through the Filename
property and use it to open the file or store the current document there.

The folder selected in the FolderBrowserDialog control is returned to the application through
the Selected Path property.

Here is the sequence of statements used to invoke the Open common dialog and retrieve the
selected filename:
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
filename = OpenFileDialog1.FileName

End If

OpenFileDialog1.FileName = "C:\WorkFiles\Documents\Document1.doc"
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
filename = OpenFileDialog1.FileName
End If

you can invoke the Color dialog box and read the value of the selected color by using the
following statements:

ColorDialog1.Color = TextBox1.BackColor
If ColorDialog1.ShowDialog = DialogResult.OK Then
TextBox1.BackColor = ColorDialog1.Color
End If

The Show Dialog method is common to all controls. The Title property is also common to all
controls and it's the string displayed in the title bar of the dialog box.
ColorDialog1.Title = "Select Drawing Color"

Rich Textbox
Rich Textboxes are similar to Textboxes but they provide some advanced features over the
standard Textbox. Rich Textbox allows formatting the text, say adding colors, displaying particular
font types
The Rich Textbox, like the Textbox is based on the Textbox Base class which is based on the
Control class.
These Rich Textboxes came into existence because many word processors these days allow
us to save text in a rich text format.
With Rich Textboxes we can also create our own word processors. We have two options
when accessing text in a Rich Textbox, text and rtf (rich text format). Text holds text in normal text
and rtf holds text in rich text format. Image of a Rich Textbox is shown below.

RichTextBox Event The default event of RichtextBox is the TextChanged event which looks like
this in code:

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


ByVal e As System.EventArgs) Handles RichTextBox1.TextChanged

End Sub

Code Samples

Code for creating bold and italic text in a Rich Textbox


Drag a Rich Textbox (RichTextBox1) and a Button (Button1) onto the form. Enter some text
in RichTextBox1, say, "We are working with Rich Textboxes".
Paste the following code in the click event of Button1.
The following code will search for text we mention in code and sets it to be displayed as
Bold or Italic based on what text is searched for.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
RichTextBox1.SelectionStart = RichTextBox1.Find("are")
Dim ifont As New Font(RichTextBox1.Font, FontStyle.Italic)
RichTextBox1.SelectionFont = ifont
RichTextBox1.SelectionStart = RichTextBox1.Find("working")
Dim bfont As New Font(RichTextBox1.Font, FontStyle.Bold)
RichTextBox1.SelectionFont = bfont
End Sub
When you run the above code and click Button1, the text "are" is displayed in Italic and the
text "working" is displayed in Bold font.
The image below displays the output.
Code for Setting the Color of Text
Lets work with previous example. Code for setting the color for particular text looks like
this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
RichTextBox1.SelectionStart = RichTextBox1.Find("are")
RichTextBox1.SelectionColor = Color.Blue
RichTextBox1.SelectionStart = RichTextBox1.Find("working")
RichTextBox1.SelectionColor = Color.Yellow
End Sub
Code for Saving Files to RTF
Drag two Rich Textboxes and two Buttons (Save, Load) onto the form.
When you enter some text in RichTextBox1 and click on save button, the text from
RichTextBox1 is saved into a rtf (rich text format) file.
When you click on Load button the text from the rtf file is displayed into RichTextBox2. The
code for that looks like this:

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


System.EventArgs) Handles Save.Click
RichTextBox1.SaveFile("hello.rtf")
End Sub
Private Sub Load_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Load.Click
RichTextBox2.LoadFile("hello.rtf")
End Sub

The files which we create using the Save File method is saved in the bin directory of the
Windows Application.

You can view output of the above said code in the image above.
Error Handling and Debugging in VB .NET
Debugging your code is something you will need to do
. Unless you write perfect code every time, there's no getting away from it.
Types of Error
Programming errors are generally broken down into three types: Design-time, Runtime, and
Logic errors.
A Design-time error is also known as a syntax error. These occur when the environment
you're programming in doesn't understand your code.
These are easy to track down in VB.NET, because you get a blue wiggly line pointing them
out.
If you try to run the programmer, you'll get a dialogue box popping up telling you that there
were Build errors.
Runtime errors are a lot harder to track down. As their name suggests, these errors occur
when the programmer is running.
An example is trying to access a file that doesn't exist.
Runtime errors usually cause your programmer to crash. If and when that happens, you get
the blame. After all, you are the programmer, and you should write code to trap runtime errors.
If you're trying to open a database in a specific location, and the database has been moved, a
Runtime error will occur. It's your job to predict a thing like this, and code accordingly.
Logic errors also occur when the programmer is running.
They happen when your code doesn't quite behave the way you thought it would. A classic
example is creating an infinite loop of the type "Do While x is greater than 10".
If x is always going to be greater than 10, then the loop has no way to exit, and just keeps
going round and round. Logic errors tend not to crash your programmer.
But they will ensure that it doesn't work properly.
Design Time Errors in VB .NET
Design time errors, remember, are syntax errors. It's when VB .NET hasn't understood what you
have typed. If that isn't clear, a few examples should explain it beter. So do the following:
 Create a new Windows project
 Add a button and textbox to your form
 Leave the Name properties on the defaults of Button1 and Textbox1
 Double click your button to access its code, and type the following:
Textbox2.Text = "Debug"
When you finish typing the line, VB.NET puts a blue wiggly line under Textbox2:

If you hold your mouse over Textbox2, you'll see a yellow tool tip appear, like the
following:

The error is occurring because you don't have a textbox called Textbox2. You'll also see this
same "Not declared" error if you try to set up a variable on the fly
As an example, change your code to this:
strText = "Debug"
TextBox1.Text = strText
Here, we are trying to put the word "Debug" into a variable called strText.
We then want to assign this variable to the Text property of Textbox1.
However, VB.NET protests about this, and puts a wiggly line under all occurrences of
strText:

Hold your mouse over the variable strText and you'll see the "not declared" tip again:

The problem this time is that we haven't declared the variable strText. Change the code to
this:
Dim strText As String
strText = "Debug"
TextBox1.Text = strText
Now that we have declared a variable, the wiggly lines will go away. If we added the variable
declaration in the wrong place, however, the wiggly lines would come back. Change you code to
this:
strText = "Debug"
TextBox1.Text = strText
Dim strText As String
If you have the Error List window open, you'll see a report of your error (If you can't see
the Task List window, from the menu bars click View > Other Windows > ErrorList):

The description of the error is "Local variable 'strText' cannot be referred to before it is
declared". If you double click the icons on the left, VB.NET will highlight the error in your code.

Move the Dim … Line back to the top, and not only do the blue wiggly lines go away, but
the Task List will be erased.

Design-time errors like the one above can be quite straightforward to correct.

Others can be quite difficult, and you'll see the blue wiggly line but not understand how to
correct the error.

The Task List should be your first port of call when faced with such an error.

Runtime errors in VB .NET

This lesson is part of an ongoing tutorial. The first part is here: Design Time Errors

Runtime errors are a lot harder than Design Time errors to track down. As their name
suggests, these errors occur when the programme is running.
Runtime errors are the ones that crash your programme. A simple way to crash a programme
is to divided by zero. Change the code for your button to this, and try it out:

Dim Num1 As Integer


Dim Num2 As Integer

Num1 = 10
Num2 = 0

TextBox1.Text = CInt(Num1 / Num2)

The CInt( ) part means Convert to an Integer. We're just making sure to convert the answer
to the sum into a number. But run your programmed and test it out.

Click your button and see what happens.

What happens is that you'll get the following error message popping up:

Click the Break button, and then stop your programmer from running.

Try ... Catch in VB .NET


This lesson is part of an ongoing tutorial. The previous part is here: Runtime Errors

VB.NET has a inbuilt class that deals with errors. The Class is called Exception. When an
exception error is found, an Exception object is created.
The coding structure VB.NET uses to deal with such Exceptions is called the Try … Catch
structure
.
In the coding area for your button, type the word Try. Then hit the return key on your
keyboard. VB.NET completes the rest of the structure for you:

Try
Catch ex As Exception
End Try
The Try word means "Try to execute this code". The Catch word means "Catch any errors
here". The ex is a variable, and the type of variable it is is an Exception object.
Move your line of code from the previous section to the Try part:
Try
rt1.LoadFile("C:\test10.txt", RichTextBoxStreamType.PlainText)
Catch ex As Exception
End Try
When you run your programmer, VB will Try to execute any code in the Try part. If
everything goes well, then it skips the Catch part.
However, if an error occurs, VB.NET jumps straight to Catch. Add the following to your
Catch part:
MsgBox(ex.Message)
Your coding window should look like

this:
Because ex is an object variable, it now has its own Properties and methods. One of these is
the Message property. Run your programmer and test it out. Click your button. You should see the
following error message:

The message is coming from the "additional Information" section of the error message we
saw earlier, the one we didn't handle.

But the point about this new message box is that it will not crash your programmer.

You have handled the Exception, and displayed an appropriate message for the user.

If you know the kind of error that a programmer might throw, you can get what Type it is
from the Error message box you saw earlier. This one:

Click the View Details links under Actions to see the following:
The first line tells us the Type of Exception it is:
System.IO.FileNotFoundException
You can add this directly to the catch part. Previously, you were just catching any error that
might be thrown:
Catch ex As Exception
But if you know a "file not found" error might be thrown, you can add that to the Catch line,
instead of Exception:
Catch ex As System.IO.FileNotFoundException
You can keep the Exception line as well. (You can have as many Catch parts as you want.) This will
Catch any other errors that may occur:
Try
rt1.LoadFile("C:\test10.txt", RichTextBoxStreamType.PlainText)
Catch ex As System.IO.FileNotFoundException
MsgBox(ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
There is one last part of the Try … Catch Statement that VB.NET doesn't add for you -
Finally:
Try
Catch ex As Exception
Finally
End Try
The finally part is always executed, whether an error occurs or not. You typically add a finally
part to perform any cleanup operations that are needed. For example, you may have opened a file
before going into a Try … Catch Statement. If an error occurs, the file will still be open. Whether an
error occurs or not, you still need to close the file. You can do that in the finally part.
But Microsoft advice that you always use Try … Catch Statements in your code. However,
throughout the rest of this course, for convenience sake, we won't be using them much. Even when
we should be. But that's no excuse for you not to use them!
Logic Errors in VB .NET
This lesson is part of an ongoing tutorial. The first part is here: Design Time Errors
The third category of errors are the Logic errors. These can be thought of as coding errors.
Your coding errors. They can be quite tricky to track down, and have you tearing your hair out with
frustration.
Dim x As Integer
Dim y As Integer
Dim answer As Integer
x = 10.5
y=3
answer = x * y
TextBox1.Text = answer
When you've added the code to your button, run your programme and test it out. Before you
click the button, what answer did you expect to get?
You'd think that 10.5 multiplied by 3 would give you the answer 31.5. Click your button. The
answer that appears in your textbox is 30!

Structured Exception Handling


Visual Basic .NET or Visual Basic 2005 offers structured exception handling that provides a
powerful, more readable alternative to "On Error Goto" error handling, which is available in
previous versions of Microsoft Visual Basic.
Structured exception handling is more powerful because it allows you to nest error handlers
inside other error handlers within the same procedure. Furthermore, structured exception handling
uses a block syntax similar to the If...Else...End If statement.
This makes Visual Basic .NET and Visual Basic 2005 code more readable and easier to
maintain.

NOTE: Visual Basic .NET or Visual Basic 2005 retains the "On Error Goto" syntax for backward
compatibility. You can still use this syntax in Visual Basic .NET or Visual Basic 2005 code.
However, you cannot combine structured exception handling and On Error statements within the
same procedure. When you write new code, Microsoft recommends that you use structured
exception handling.

The basic syntax of structured error handling is as follows:


Try
'Code that may raise an error.
Catch
'Code to handle the error.
Finally
'Code to do any final clean up.
End Try

The Try and End Try statements are required. The Catch and Finally statements are not
required, though you must include at least one of them in your code.
You can also specify multiple Catch statements so that each Catch block handles a specific
error.

Catch an Exception

1. Start Visual Studio .NET or Visual Studio 2005.


2. Create a new Console Application project in Visual Basic .NET or in Visual Basic 2005.
3. In the Sub Main procedure, add the following code:
4. Dim a As Integer = 0
5. Dim b As Integer = 0
6. Dim c As Integer = 0
7.
8. Try
9. a = b \ c
10. Catch exc As Exception
11. Console.WriteLine("A run-time error occurred")
12. Finally
13. Console.ReadLine()
14. End Try
15. On the Debug menu, click Start to run the application. The code tries to divide a number by
zero. This is an illegal operation that causes a divide by zero exception. Fortunately, the
Catch block catches this error, and the Console window displays the following error
message:
16. A run-time error has occurred
17. Close the Console window.

Catch Multiple Exceptions


This section demonstrates how to use multiple Catch statements to handle different errors.

1. Open the Console Application project that you created in the previous section.
2. In the Sub Main procedure, replace the code that you copied in the previous section with the
following code:
3. Dim a As Integer = 2147483647
4. Dim b As Integer = 0
5. Dim c As Integer = 0
6.
7. Try
8. a += 1
9. Catch exc As DivideByZeroException
10. Console.WriteLine("Error: Divide by zero")
11. Catch exc As OverflowException
12. Console.WriteLine("Error: Overflow")
13. Finally
14. Console.ReadLine()
15. End Try

This code includes two Catch blocks: one to catch the previous divide by zero

error, and one to catch the new overflow error.

16. On the Debug menu, click Start to run the application. The Console window displays the
following error message:
17. Error: Overflow
18. Close the Console window.
19. Because you cannot always anticipate every error that may occur, you can add a Catch all
block for unanticipated exceptions. For example, add the following code before the Finally
statement to catch any unanticipated errors and display the appropriate error message:
20. Catch exc As Exception
21. Console.WriteLine("Error: " & exc.Message)
22. On the File menu, click Close Solution.

Throw an Exception
Structured exception handling uses the Catch statement to catch an exception. Structured
exception handling also provides a way to throw an exception
For example, it is useful to throw an exception when you perform data validation inside a
Property Set procedure because you may want to throw an error if a business rule is violated.

Catch an Exception
Module Module1

Sub Main()
Dim a As Integer = 0
Dim b As Integer = 0
Dim c As Integer = 0
Try
a = b \ c
Catch exc As Exception
Console.WriteLine("A run-time error occurred")
Finally
Console.ReadLine()
End Try
End Sub
End Module

HOW CAN YOU ACCESS DATABASE IN VB.NET?


 The connection object is what you need if you want to connect to a database.
 OLE stands for object linking and embedding, and its basically a lot of objects(com
objects)Bundled together that allow you to connect to data sources in general, and not
just data databases
 So place click your button on your form. Change the name property to btnload.
 Double click your button to open up the code window. Add the following line:Dim con As
New OleDb.OleDbConnection
 At the very top of your code window, before public class form1, type the following.

Imports System.data
Public class from1
Private sub btnLoad_Click(ByVal sender As System.Object,ByVal e As
System.EvetArgs)Handles btnLoad.Click
Dim con As New OleDb.OleDbConnection
End sub
End class
Setting a connection stringing:
 There are properties and methods associated with the connection object.
 We want to start and with the connection property.
 We need to pass two things to our new connection object; the technology we want to
use to do the connecting to our database; and where the database is. The technology is
called the provider; and you use “data source” to specify where your database is.

Con.connectionstring=”provider=Microsoft.jet.OLEDB.4.0;data source=c:\addressbook.mdb”
Opening the connection:
 Now that we have a connectionstring , we can go ahead and open the database.this is quite
easy-just use the open method of the connection object:con.open()
 Once open,the connection has to be closed again.this time, just use the close method:
Con.close()
 Add the following four lines to your code:
Con.open()
Msgbox(“a connection to the database is now open”)
Con.close()

Msgbox(“the connection to the database in now closed”)


DISCUSS ABOUT ADO.NET DATA OBJECTS.
(OR)
DISCUSS ABOUT AN OVERVIEW OF ADO.NET DATA OBJECTS.
 A connection object contains a connection string that stores the name of the data provider,
name of the database, username and password for connecting to the database.
 Visual basic can also work with any data provider that can support open database
connectivity (ODBC), such as MySQL or Sybase.
 To work with SQL server, use ado.net sqlconnection objects; oracle connection to work with
database; and ADO.NET oledbconnection objects to work with any other data provider.
 After creating the connection object for connecting to the database, we create a data adapter
object to work with the data accessed from the database.
 A data adapter objects work like an interface between a data source and a dataset.
 A data object can be termed as a logical collection of data.
 A data adapter object fills the dataset object when data is accessed from the database.
 Data contained in the dataset object when data is accessed from the database.
 Data contained in dataset can be displayed in any data display controls, such as
datagridview, detailsview, combobox or textbox.
 A data display control is used to display data on a user interface.
 The three objects to connect and retrieve data from the database are-data connection for
connect ing to the database, data adapters to execute the SQL
query, and datasets to store the data retrieved from the database.
WORKING WITH ADO.NET:
DISCUSS ABOUT THE MOST COMMON ADO.NET OBJECTS.
 Data connection object-To start working with a database,you must have a data connection.
 Data adapters-Data adapters are a very important part of ADO.NET.They are used to
communicate between a datasource and database.
 Command objects-Data adapters can read,add,update,and delete records in a data source.
 Datasets-Datasets store data in a disconnected cache.The structure of a dataset is similer to
that of a relational database.
 DataTable objects-DataTable objects hold a data table from a data source.
 DataReader objects- DataReader object hold a read-only ,forward-only set of data from a
database.
 Data views-Data views represent a customized view of a single table that can be
filtered,searched, or sorted.
 Constrained objects-Datasets support constraints to check data integrity.
 DataRelation objects-DataRelation objects specify a relationship between parent and child
tables,based on a key that both tables share.
 DataRow objects-Datarow objects correspond to a particular row in a data table.
 DataColumn objects-DataColumn objects correspond to the column in a table.
WRITE SHORT NOTES ON BASIC SQL SELECT STATEMENT WITH
EXAMPLES.
SELECT:
Used to retrieve values for some or all of the fields from a table.
Syntax: SELECT * FROM customers.
Example: SELECT cutomers ID,Address,City FROM Customers.
WHERE:
To specify a criteria that you want records to meet.
SELECT * FROM customers WHERE City=’trichy’
BETWEEN:
To indicates a range of values you will accept.
SELECT * FROM Customers WHERE CutomerID BETWEEN ‘h*’ AND ‘I*’
IN CLAUSE:
To match the value for a given field of the table from a set of specified values.
SELECT * FROM Customers WHERE City IN(‘trichy’,’salem’)
LIKE CLAUSE:
It is used to match value of a field in a table, with some specified pattern.
SELECT * FROM Customers WHERE City LIKE ‘DH%’
DISTINCT CLAUSE:
A database has duplicate values in the fields of the records of a table. We use DISTINCT
clause for selecting the values in the fields without duplication.
SELECTDISTINCT City FROM Customers

LOGICAL OPERATION:
Three logical operator AND,OR,NOT. Using AND both condition in the WHERE clause must
be True; when using OR, at least one of the conditions should be True and when using NOT, the
value of the clause flips from True and False.
ORDER BY CLAUSE:
Arrange the records in an order in the dataset.
SELECT * FROM Customers ORDER BY customerID Desc
You can also retrieve the record arranged in the descending order of
CustomerID from the Cutomer’s table.
AS CLAUSE:
When you are accessing records from a table, you can refer the fields with some more
descriptive names using AS clause.
SELECT ContactName AS Name FROM Customers
GROUP BY CLAUSE:
You can group records using GROUP BY clause.
SELECT * FROM Customers GROUP BY city
HAVING CLAUSE:
You can specify additional criteria for the records you want to retrieve.
SELECT * FROM Customers GROUPBY City HAVING City LIKE ‘Lo%’
DELETE STATEMENT:
To delete records from a table.
DELETE * FROM Customers WHERE City NOT IN(‘trichy’,’salem’)
UPDATE STATEMENT:
To update a database.
UPDATE Customers SET City=’trichy’ WHERE City=’tn’
JOINING TABLE:
SELECT Customers.ContactName,Orders.OrdersID FROM Customer ,Orders WHERE
Cutomers.CustomersID=Orders.CutomersID
WRITE SHORT NOTES ON AGGREGATE FUNCTION IN SQL.
SUM():
Return the tital of a column’s volues.
SELECT “total quality”=SUM(qty) FROM sales
MAX():
Return the maximum value for a column in a table or set of rows returned in aquery.
SELECT “Maximum Quantity”=MAX(qty) FROM sales
MIN():
Return the minimum value for a column in a table or set of rows returned in aquery.
SELECT “Minimum Quantity”=MIN(qty) FROM sales
AVG():
Calculate the average value of a column in a table or in a set of rows,depending on how it is used.
SELECT ”Average Quantity”=AVG(qty)FROM sales
COUNT():
Returns the count of rows in the query.
SELECT COUNT(*) FROM authors
CONVERT():
To ensure that you have the correct data types ti perform an operation.
SELECT title,royalty,”saless”=CONVERT(char(7),ytd_sales)FROM titles
GETDATA():
Return the current date and time from the server’s system clock.
SELECT GETDATE()
DITEDIFF():
Compare and return the difference between data items, such as days,weeks,minutes, and hours.
SELECT ord_date,”days difference”=DATEDIFF(dd,ord_date,GETDATE()) FROM sales
DITEPART():
Returns a value equals to the part of a date that you specify.
SELECT ord_date,”days of the week”=DATEPART(dw,ord_date)FROM sales
SUBSTRING():
Any string manipulation can be accomplished with this function in conjunction with a few string
operator and some other basic string function.
SELECT SUBSTRING(title,4,100) FROM Titles
LEFT() and RIGHT():
They are specially designed to work with the left or right end of the string you are manipulating.
SELECT LEFT(titles,20)FROM Titles
SELECT RIGHT(titles,20) FROM Titles
UPPER():
Converts the string passed to the function into all uppercase characters.
SELECT UPPER(au_fname) FROM authors
RTRIM and LTRIM:
RTRIM() removes any trailing blanks from a string or column.
LTRIM() works the same way as RTRIM() except that it removes blanks from the beginning
of a string instead of the end.
LEN():
To return the number of character of a given character string.
SELECT LEN(‘welcome’)
REPLICATE():
Return a character string which is repeated a specified number of times.
SELECT REPLICATE(‘-’,50)
SPACE():
Returns the specified number of spaces.
SELECT SPACE(10)+au_fname FROM authors
STR():
Converts a numeric value to character data.
SELECT STR(7238.26,6,1)
CHAR():
Returns the character that corresponds to the ASCII code passed as an integer to the function.

HOW CAN WE MANAGE DATABASES USING SERVER EXPLORER? (OR)


DISCUSS THE FOLLOWING CONCEPTS.
1. CREATING A NEW DATA CONNECTION
2. CREATING A NEW DATABASE
3. CREATING A NEW TABLE
4. ADDIING DATA TO TABLE
5. SELECTING DATA FROM A TABLE
6. DROPPING A TABLE
7. DELETING A DATABASE CONNECTION
CREATING A NEW DATABASE CONNECTION:
 Create a new window application and create a data connection to the authors table in the
Microsoft SQL server’s pubs database using the server explorer.
 To add a connection to the pubs database, right-click the ‘data connections’ icon in the
server explorer and select the ‘add connection’ option or use the ‘Tools| connect to
database’ menu item.
 In the ‘add connection ‘dialogbox, you can select the data source of tour choice by clicking
on the ‘change’ button.
 You can choose oracle database, Microsoft ODBC Data source, Microsoft SQL server
Database, or any other Database.
 Enter ‘username’ and ‘password’.
 Specify the data source and the database name to work with, click the ‘Test connection’
button. If the connection is working a message box with ‘Test connection succeeded’. When
the connection is set, click on the ‘OK’ button to close the ‘Add connection’ dialog box.

CREATING A NEW DATABASE:


 Right click on the ‘Data connection’ icon in the server explorer and select ‘create new SQL
server Database option from the context menu.
 Select the name of the server in which you want to create the new database, Then select the
authentication type –Windows or SQL server Authentication.
 Select the second option. After that add new database name that you want to create and then
click on the ‘OK’ button. This will create a new database with the name ’MyDatabase’.

CREATING A NEW TABLE:


 To add the tables expand the newly created database node and right-click on the ‘Tables’
icon for menu o appear.
 Then select ’Add New Table’ option from the context menu. Doing this will open a table
prompting for column name, data type, and allow nulls option.
 Selecting this option marks that column with a key shaped icon and sets the column to
display unique user ids.
 Then close the window and you will be prompted to save the changes from the table.
 The moment you select the ’Yes’ button, another window, choose Name, opens prompting
you to enter the name of the table.
 If you do not specify any name, by default, it takes the table name as ‘Table1’.
 Specify the table name as ‘Users’ and click on the ‘OK’ button to return to the server
explorer window.

ADDITING DATA TO A TABLE:


 After you create a table, you might requiring adding data into it. To do so, right-click on the
Users table and select ‘Show Table Data’ option.
 Then enter data for the table and close the window. This will save the data entered in the
table.

SELECTING DATA FROM A TABLE:


 Right-click on User’s table and select a ‘New Query’ option.
 This will open an ‘Add Table’ dialog box. Click on the ‘Add’ button to add the table and
then select the ‘Close’ button.
 This will add the users table for the query.
 You can either select all columns or select some of them for retrieving the data.
 After the columns, you can notice a select statement at the bottom of the window.
 Now clicking on the exclamation sign on the toolbar to execute the query.

DROPPING A TABLE:
 Sometimes you may not need a table during the transaction.
 In such a case, you can drop or delete it directly from the ‘Server Explorer’.
 To delete the user table, right-click on it and select the ‘Delete’ option from the context
menu.
 Clicking on the ‘Delete’ option display a message box asking the user whether to
permanently delete the table from the database.
 Click on the ‘Yes’ button if you want to delete the table permanently.

DELETING A DATABASE CONNECTION:


 The database connection is no longer needed and you want to delete it, you can do so by
right-clicking on the database name in the Server Explorer and selecting ‘Deleting’ option
from the context menu.
 When you select the ‘Delete’ option, a message box is displayed asking the user for the
confirmation, whether to remove the database connection. Click on ‘Yes’ button to remove
the database connection permanently.

DISCUSS ABOUT ACCESSING DATA WITH DATA ADAPDER AND DATASET.


There are two ways to display data on a form-either you can display the entire table on a form or
only few fields from a table.
 To create the application, first add on OleDbDataAdapter control to the form from the ‘Data’
tab of the toolbox.
 When you drag and drop the OleDbDataAdapter object, it will be displayed in the
component tray.
 Doing so opens the Data Adapter Configuration wizard.
 Click the ’Next’ button in the data adapter configuration Wizard to choose the data
connection you want to use.
 Click ‘Next’ to choose a command type for the adapter. In the next dialog box, select ‘Query
Builder’ button to build the query, the ‘Add Table’ dialog box will be opened.
 In the ‘Add Table’ dialog box ,add the table from which you want to retrieve the data.
 Now first click on the ‘Add’ button to the add the table to the query builder and then click on
the ‘Close’ button to close the ‘Add Table’ dialog box.
 When you choose the Add Table window, the Query Builder dialog box with the tables gets
displayed.
 Next. Click on the ‘OK’ button to create the SQL statement. When you click on the ‘Next’
button in the Data Adapter Configuration Wizard, the wizard configures the data adapter and
report the result. Press the ‘Finish’ button to close the Data Adapter Configuration Wizard.
UNIT-IV

ASP.NET:

ASP.NET is a server side scripting technology that enables script (embedded in web pages)
to be executed by an Internet server.

 ASP.NET is a Microsoft technology


 ASP stands for Active Server Page
 ASP.NET is program that runs inside IIS
 IIS(Internet Information Services) is Microsoft’s Internet Server
 IIS comes as a free component with Windows servers
 IIS is also a part of windows 2000 and XP Professional

INTRODUSING WEB DEVELOPER TOOLS:


There are many text and web pages editor that can be used to create web applications.

 Exploring Visual Web Editor:

 There are many windows, controls and toolbars within the user interface.
 When you start your program, a Start Page provides access to your recently created
applications and links to the MSDN support site, additional tools, and tutorials
available name on the start page to reopen the application quickly.
 If you have closed the start page and want to reopen it, click View on the menu bar,
select other windows, and then click start page.

 Exploring the individual windows:

 The properties window is used to set properties for objects, controls and classes.
 The main window is used to view your project file.
 The solution Explorer windows is used to manage all the files and resources within
your web applications.
 The data explorer window is used to create and manage connections to database and
to manage data objects such as tables and stored procedures.
 The Toolbox window contains frequency used control.

The following about the General and other tabs of the Toolbox:

Standard tab: Contains many of the Asp.net controls that are used within Asp.net pages.
Data tab: Provide access to data controls used to display data , and data source control.
Validation tab: Provides access to data controls used to validate web pages.
Navigation tab: Provides access to controls used to create site maps, menus and data sources.
Login tab: Provides access to controls that are used to create a login, password recovery and
change password forms, controls to view the visitor’s login status, and wizards to create users.
Web part tab: Provides access to create and manage a new way of organizing web parts and
web zones.
HTML tab: Provides access to the traditional HTML tags.
General tab: Does not contain any controls by default.

 Auto hide Property:


 The auto hide property is a new feature that allows you to store the window on the
desktop as a tab.

 Dock able property:

 The dock able property to be moved to other locations on the desktop and to be
placed on top of one another.
 Floating Property:

 The floating property allows to select the windows and drag and drop it to any
locations on the desktop.

 Creating a New web applications:

1. Start your web editor applications.


2. To create a new project, click the file on the menu bar and click new web site. The New
Website window opens. ASP.NET Website. By default, File System is selected in the
location drop-down list.
3. To locate click the browse button, which opens the choose location window.
4. Navigate through your file System to locate and click [your student folder].
5. You need to create a new folder within [your student folder] to store your first web
application. To do so, click the create new folder icon, type website1, and then press
enter. The complete file path to your new web application will be displayed in the folder
textbox.
6. Click open, which closes the choose location window.
7. Click ok to create your web application and close the website window.
8. To close the web application, click file on the menu bar and then click close project.
9. To exit, click file on the menu bar and click exit.

INTRODUCTION TO ASP.NET SERVER PROGRAMMING


Programming that makes it possible for client applications to communicate with server
applications in a network is referred to as client-server programming. Active server pages .NET or
ASP.NET a product to Microsoft is mainly used to create client-server applications. Because these
client-server applications communicate primarily through the internet and are simply referred as
Web Application.

Before there were client-server Applications


 As the internet expanded from governments and universities to business and individuals, web
applications needed to become more dynamic.
 A dynamic web application enables the user to interact with the application in ways that
change the appearance or the contents of the web page.
 Examples of dynamic web application include shopping carts, membership databases, online
catalogs, and personalized web sites.
 Unfortunately, you cannot create dynamic web application using HTML alone.
However, you can use many other different technologies along with HTML, including client-
and server-side scripting and server-side programming, to create dynamic web application.
 A major limitation of client-side scripting is browser dependency, because client-side scripts
are executed via the browser's scripting engines and not all browsers support all scripting
languages.
 Another major limitation of client-side scripting is security. The use of the client can easily
view the scripts within the web page.

Processing ASP.NET Application


o A basic web page created with ASP.NET is referred to as a web form. web form
allow you to quickly develop and process forms on web pages and develop cross-
browser web applications.
o Web forms are web pages identified with the file extension .aspx
o Any page ending in .aspx is directed to the ASP.NET engine, which is located on the
server in a file named aspnet_isapi.dll.
o The developer creates web page which is stored on the web server. Programming
code can be precompiled into the assembly or compiled at the first runtime.
o The assembly contains a language - and computer -independent representation of
your code called the Microsoft intermediate Language (MSIL).
o When the visitor first requests the page the ASP.NET engine dynamically compiles
the assembly and on subsequent requests the page is translated into computer-specific
instructions with the output sent back to the browser, or version of HTML.

Server Control
 ASP.NET provides a way to use server controls. These server controls are objects on the web
server built from classes that were installed when you installed .NET framework.
 These server controls, such as HTML controls and ASP.NET controls, can be used only
within ASP.NET pages -that is, within pages that end in .aspx.
 Important to understand that server controls will generate the output that is compatible with
the browser. Server controls can be configured to target a specific browser, or version of
HTML.
 These server controls generate the necessary HTML tags, JavaScript, and dynamic HTML,
which are supported by the client.

HTML Tags and HTML Controls


 HTML controls are similar to HTML tags, except that they are programmable by the server.
 In traditional HTML page the developer creates a textbox by writing
 <input id="Text1" type="text"> HTML tags are sent unaltered to the browser, user needs to
add runat="server" to the tag to transform the HTML tag into an HTML control.
 The HTML controls generate the HTML tags are sent to and then rendered in the browser.
Web controls
 Web controls allow you to render HTML output and provide more flexibily than HTML
controls when you are creating your programs.
 Web controls will create the HTML tags that are sent to the browser.
 Web controls are usually identified with the prefix .asp: followed by the name of the
control..
 Eg: Create button control is <asp: Button ID="Button" runat="server" Text="show the
message"/>
 Web controls have different properties than their HTML control counterparts. Web controls
can interact with client-side events such as the user clicking a button. When the events occur,
the web control trigger a script to run on the server.

Creating a web page using a web editor


 Click file on the menu bar click new file.
 Click web form in the add new item window.
 In the name text box, highlight the existing content, type ch_1 sample.aspx, and then click
add.
 Type the code.
 Click file on the menu bar, and then click save all.
 Click file on the menu bar, and then click view in browser.
 Right-click the page in the browser and click view source.
 Select all of the text in source code view.
 Open a browser window, type http://validator.w3.org/ in the address text box, and then press
enter. The markup validation service web page opens.
 Scroll down to the validate by direct input text box, right-click inside the text box, and click
paste.
 Close the browser and all of the open files in your web editor.

USING VARIABLES AND CONSTANTS IN A WEB FORM

Variables are store that can be retrieved at a later time. A variable declaration consists of
three parts: i. The declaration keywords ii. A variable name iii. Data type. The data type identifies
what kind of data the variable can store.

Declaring a variable:

 Declaring a variable is the process of reserving the memory space for the variable before it is
used in the program.
 Local variable are defined within a procedure and can be used only by the procedure in
which they were declared.
 Module-level variables are defined in the class but outside of the procedures, and can be
used by any one of the procedures within the page.
 The scope identifies what context of the application can access the variable.
Dim: with no other keyword, its use will mean the variable is public.
Public: This is used to declare a variable global or public, and therefore available to other
locations within same we page or form outside the web form.
Friend: This defines variables that are used only within the current web application or
project
Protected: This defines variables that can be used only by the procedure in which they were
declared.

Naming variables
 You cannot use any one of the visual basic.NET commands or keywords as your variable
name.
 Variable names must begin with a letter.
 You cannot use a period or space within a variable name.
 Avoid using any special characters in a variable name except for the underscore.

Assigning values to variables


 To assign a value to a variable, enter the name of the variable on the left side of the
assignment operator, and enter the new value on the left side of the assignment operator, and
enter the new value on the right side of the assignment operator.
 You can assign the value to the variable when you declare the variable or after the variable
has been created.
 Example: Dim CompanyName As String="Barkley Builders"

Declaring Constants
You can use a constant instead of a variable when you want o assign a value that does not
change. The Const keyword is used to declare a constant.
Example: Const TAXRATE As integer=8

WORKING WITH WEB OBJECTS TO STORE DATA

HTTP is one of the protocols used to send and receive data over the Internet. The header is
the portion of a data packet that describes how and where to send the file. The user agent can be
used to identify the client software.

Using the Request object to Retrieve Data from the header

HTTP collects information and stores the values as collection server variables.
The Request object of the page class allows you to retrieve any data sent by the browser,
including the names and values of the form fields and the server variables.
Server variables can be retrieved by using an HTTP request object with Request .server
variables ("VARIABLE_NAME"). The server variable name is always in uppercase.

Retrieving Data from a form with the request object


 The request object contains a form collection and QueryString collection that allow you to
retrieve form data from the header.
 If you use HTML elements to create your form, you must request the form or QueryString
collections to retrieve the form field values.
 If the values of the form method identified in the HTML form element is Post, then the form
is sent as part of the HTTP request body.
 To retrieve the value of a field named CompanyName, you would enter Request. Form
("companyName").

Accessing Form Field Data


 If you are processing server controls on the web page, you can access the value properties of
the form field directly from your web page code.
 The property name that you use to access the value is different for each type of server
control.
 To retrieve the value of the form field, you simply use the name of the object and the
property that store its value, such as CompanyName.Value.
 To assign a value to the form field such as form field such as CompanyName.Value="Green
River Electronics".

Working with the Response Object


 The page class also contains a Response object, which is used to send information to the
browser.
 The cookies collection is used to send cookies to the browser, which are then written by the
browser in a cookie file within the client's cookie directory.
 A status code is sent to indicate whether the browser requests was successful or encountered
an error.
 You can access status codes with a custom error message page.
 The Response object has several methods to send contends to the browser.

Session Objects
 One of the biggest challenges in creating interactive web pages is maintaining the state of the
user.
 User information can be tracked across user sessions and across the entire applications.
 A special session cookie is used to maintain the session information.

DESIGNING .NET WEB APPLICATION

Visual Basic .NET is used as the programming language for both types of applications.
ASP.NET is the technology used to develop dynamic web applications within the .NET framework.
The .NET framework consists of a common language runtime (CLR) and a hierarchical set of base
class libraries.

Web Application Architecture

Both the logical and physical tires are related in an enterprise environment. The presentation
tier contains the user interface. The business programming logic, such as the formulas to calculate
interest rate, is implemented in components at a middle tier. It is useful to create the business
components to isolate the programming logic so that changes within the visual layer would not
impact the programming code. The data tier often consists of one or more data servers such as SQL
server. Making the application support a large number of visitors are called scaling. Scaling may
require adding more web servers to handle the requests, to deliver applications, and to store and
cache data. Scaling the application should not result in recording in well-designed application.

Organization of classes in the .NET framework


The base class libraries are groups of commonly used built-in classes stored in executable
files. These classes can be accessed from any .NET application. They contain fundamental code
structures and methods that allow you to communicate with the operating system software and other
applications. The base class libraries are organized into hierarchical logical groupings of code called
namespaces. The System namespace is at the top of the namespace hierarchy, and all built-in classes
inherit from it. For example, the web controls are objects created by classes that are located within
the System.Web.UI.Control.WebControl namespace.

PROGRAMMING WITH VISUAL BASIC.NET:


Creating a class in ASP.NET
Using a Procedure
Creating a Property Method
How the Applications interact with the Systems.Drawing.Graphics class
Using the Systems.Drawing.Graphics class
Creating a class in ASP.NET:
 ASP.NET application stores programming statements in classes. An object is set of
related compartmentalized code that is based on class.
 The creation of an object consists of two separate parts.
 The first task is to create the object definition, also called the base class or Class
definition. It is the code that will be used to create the procedures and properties of the
objects. Instantiation is process of declaring and initializing an object from a class.
 The source file for the class ends in .vb. You can restrict which applications can
have access to the class using these additional keywords.
 Public: Can interact with other objects outside of the base class.
 Private: Can only be called with in the base class
 Protected: Can be called from within the base class and within subclasses;
subclasses are used to create a class that inherits from a base class.
 Friend: Can be called anywhere from within the same application.
A component is class with a visual or graphical user interface. The code follows is a
sample of how to create a class definition named MyClass in web application named
GreenRiver web:
Public class MyClass
Private companyName As String=”Green River Electronics”
End Class.
You must use the keyword Dim to declare variable in which to store the object, and the
keyword New to identify that is an object based on a class definition.
In the class in the sample code below, the MyNewClass object is based on the MyClass
classs:
Dim MyClass As New GreenRiver Web.MyClass()
Using a Procedure:
 Procedure are used to contain one or more programming statements. This are executed only
when they are called by another when an event occurs.
 It is always execute in the order in which they are called,not the order in which they are
created.
 You can call the procedure several times, passing different arguments each time.
 Creating subprocedures
 Creating Event Procedures
 Page Events
 Creating function
Creating Subprocedures:
 A subprocedure is a procedure that can be called from other locations.
 Subprocedure do not return values and cannot be used in any expression value
 When you create the subprocedure,declare it public or private.
 Subprocedures are declared using the keyword Sub.
Syntax:
Sub SubprocedureName(CompanyName As String,-TotalEmployees As Integer)
Programming statements go here
End sub
Creating Event Procedures:
 It is type of subprocedure that is attached to an object with events.An event procedure
is not executed until triggered by an event.
 Different objects have different event.Event procedure names are based on the name of
the object and event name.An underscore (_) is used to separate the object name and
the event name.
The following is the syntax for creating a basic event procedure:
Sub objectName_event(Sender As Object, e AsEventArgs)
Programming statements go here
End sub
Page Events:
A static HTML page interprets the code line by line.
A page event is, quite simply, an event that occurs within the page lifecycle
The first time a page is requested by a client, a series of page events occurs,
 Page _Init event:
 It initializes the page framework hierarchy, creates all of the controls,deserializes the
Viewstate,and applies the previous settings to the control.
 Page_load event:
 Loads any server controls into memory and occurs every time the page is requested.
 Page_PreRender event:
 It occurs immediately before the control hierarchy is rendered and sent to the
browser.
 Page_Unload event:
 The page is removed from the servers’s memory.
Creating Functions:
 A function is a block of code that is grouped into a named unit.
 There are hundreds of built _in functions available within the .NET framework
 Including date and time,string and formatting functions,among others.
 The End Function statement is used to identify the end of the function,can leave the
function at anytime by inserting the insert the Exit Function Statement.
 The data type returned is identified in the function declaration.

Creating a proprety method:


 A property sets the value of a variable defined within an object used to expose private
variables that are defined within the class.
Public Readonly Property StoreName() As String
Return StoreName
Endget
Endproperty

How Web Applications Interact with the Systems.Drawing.Graphics Class:


There are many additional classes that can be used to display content in the graphic,as follows
 DrawString class:
Draw text to the bitmap
 FillRectangle method:
Create Rectangles and squares
 Fillpolygon mehod:
o Create polygon shapes such as triangles,trapezoids,and octagons.
 Point class:
o Create and Connect individual points within the polygone.
 FillElllipse method:
o Create Circles and ovals.
 Fontclass:
o Set the font type and size for a text message.
 Brushes Enumerator:
Change the color of the brushes.
 Pen class:
Choose different styles of pens using the LineCap and DashStylepropertise.
 LineCap property:
o How to start and end the line.
 DashStyleProperty:
Used to alter the line style and and can be solid,dash,dot,dashdot,dashdotdot,or custom.
 Smoothing mode property:
 Set to AntiAlias,which will smooth any curves.
 Dispose method:
Closes the images and releases the memory so that the image source file can br used with
other applications.
Dynamic Creating Server controls:
 The placeheader control is used as container to store dynamically added server controls.
 The Panel control can contain other controls and creates a DIV tag to enclose the contents.
 The Literal control to write content directly to the page.
 The hyperlink control is used to create an anchor tag that can link to another page or target
by using the ImageURL property.The displayed content is configured using the Text
property.
 The toolTip is new property that is used to display message when the user places the pointer
over the object.

Dynamically Creating a HyperLink Control:


The Literal is used to send HTML line break tags to the browser. The placeholder control is
created within a panel control,which is used to position the controls on the web form.
ADVANCED WEB CONTROLS
 The Ad rotator control
 The calendar control
 Using file upload control

The Ad rotator control:


It allows you to display a banner ad on a Web Page. When you refresh the page, the banner
and is changed to another image.
The Ad rotator control is created from the System.Web.UL.WebControl.Adrotator
namespace.
Understanding the properties of the Ad rotator control:
 The height property and width property define the height and width of the image that will be
displayed.
 The style property within Visual Studio.NET to configure the styles for the Ad rotator
control.
 The target property is set to top by default.
 The keyword Filter property retrieves only those banner ads from the XMLdocument whose
keyword matches exactly.
 The Tooltip property is used to provide more information about the banner ad.
The calendar control:
Use the calendar control to insert and configure an interactive calendar within the web page.

The calendercontrol is useful for allowing a user to select dates for plane,hotel,and
conference reservations.
It is used to display event data such as the location and timo of the event.
It is created by the calendar class .
The calendar control is System.Web.Controls.Calendar
Support properties,Methods,and Events:
The various calendar control properties that can be configured are follows
DayHeaderStyle:
Sets the style for the days of the weeks
Day style:
Sets the styles for the individual dates.
NextPrevStyle:
Sets the styles for the navigation controls in the heading.
OtherMonthDayStyle:
Sets the style for the dates that are not in current month
SeletedDayStyle:
Sets the style for the dates that are selected.
SeletorStyle:
Sets the style for the month date selection column.
TitleStyle:
Sets the style for the title in the heading.
TodayDayStyle:
Sets the style for the current date.
WeekEndDayStyle:
Sets the style for the weekend days.
Other properties that allow to modify the calender control’s appearance include the following:
ShowDayHeader property:
Show or hide the day’s of the week heading row.
ShowGridLines property:
Show or hide the gridlines that divide the days of month.
ShowNextPrev property:
Show or hide the navigation controls.
ShowTitle property:
Show or hide the title in the heading.
Using File Upload Control:
The file upload control allows you to upload a file to a web server. There are many
uses for a File Upload control, such as the following:
Online store, community and volunteer organizations, businesses.

 Uploading a file with the FileUpload Control:


 Sending E-Mail from the Web page
 Storing and retrieving data in the web server’s file system

Uploading a File with the FileUpload control:


It contain several properties that you may access before you upload the file;
HasFile property:
Specifies if the File Upload control contains a file.
File Name property:
Retrives the complete file name on the client’s computer.
File bytes property:
Identifies actual bytes in the file stored as an array.
File Content property:
Is a stream output of the File content
Sending E-mail from the Web page:
To send outbound email from a web page, you must use an e-mail server, along with an e-
mail object or application to communicate with the email server.
Storing and retrieving data in the web server’s file system:
There are several classes and objects with in the system.IO namespace that allow you to
interact with the web server’s file system.
The system.IO namespaces allows synchronous and asynchronous reading and writing of
data streams and files.
The system.IO namespace contains at several classes such as File,FileStream,and
Diretory,that allow you to create, read and delete files.
The FileSystem info class is the base class for both the FileInfo class and the DiretoryInfo
class.

MANAGING DATA WITH ASP.NET


 Inserting,Modifying,And Deleting Records
 Data Management
 Securing DataBases
Inserting , Modifying and Deleting records:
 To maintain a database you must be able to create new records,modify,existing records,
and delete records.
 You either can use the command builder method built into the GridView,DataList and
Repeater controls to help you build methods and procedures to maintain the databases.
Using the GridView Control to maintain a database:
 The Grid view control allows to bind data to the columns in the database.
Filtering Data with the GridView control:
 Parameters passed to the select statement are called Selectparameter objects and are
collectively called the SelectParameters collection.
 There are also InsertParametr, UpdateParameter, DeleteParameter, and Filter Parameter
objects for the insert, update, delete, and filter queries.
You can retrieve the parameter from the value from any of the following sources.
 ControlParameter,
 CookieParameter,
 FormParameter,
 ProfileParameter
 QueryStringParameter
 Session Parameter
Sorting Data with the GridView Control:
The Grid View control can easily be configured to support sorting data from the
DataSource object by setting AllowSorting property to True..
Editing a New Record with the GridViewcontrol:
You can write custom code to insert, edit or delete records, or you can use the methods
built into the data controls.
In the following exercise, you will use the built-in methods of the GridView control to
modify records.
1. Right-click the ch10_GridViewEdit1.aspx page in the solution Explorer window
and select View in Designer.
2. Click the, <smart> tag to open the Task List for the AccessDataSourcel control and
select configure Data Source.
3. Click the,<smart> tag to open the Task List for the GridView control and then click
Auto Format. Select the Mocha schema and click ok.
4. Click the <smart> tag to open the Task List for the GridView control and then in the
choose Data Source text box select AccessDataSource1 from the drop-down list. Then click the edit
columns hyperlink. In the lower-left text box, click Edit, Update, Cancel.the properties for this
Command Field column appear in the right of the window. Change the ButtonType property from
link to Button as shown in figure 10-4. click ok.

Deleting a New Record with the details View


You can write code to delete records in the GridView control. In the following exercise; you will
use the built-in methods of the GridView control to modify records.
1. Right-click the ch10_GridViewDelete.aspx page in the solution Explorer window
and select View in Designer.
2. Click the, <smart> tag to open the Task List for the GridView control. Click
Enable Editing and Enable Deleting.
3. Click the Save All icon. Right-click the page in the solution Explorer window and
then select View in Browser.
4. Click the Delete hyperlink for the Bridal category.
Inserting a New Record with the details View control:
You can write code to insert or delete records, or you can use the methods built into the Data
controls.
In the following exercise, you use the Details View control to create new records.
1. Right-click the ch10-Details ViewInsert.aspx page icon in the solution Explorer
window and select View in Designer.
2. Click the <smart> tag to open the Task List for the Details View control.
3. Click the save all.
4. In the browser, click the New hyperlink. Insert the values for the Bridal record.
Category ID (28), Category Name (Bridal), Image (28.jpg), Thumbnail (28.gif)…….as fig
10.10.click the insert button. Close the browser and weg pages.

Using a Form View Control:


You can use a Data control, such as a DropDownList or RadioButtonList to retrieve the record that
you want to edit.
Data Management:
With visual studio.NET, you can create SQL queries and stored procedures. Stored
procedures are SQL queries that are stored with the database and can be reused.
 Stored procedures execute faster and are more secure than passing SQL queries.once you
create the stored procedures in the database, you can call it from a web page and cause it
to execute.
 In SQL server,SQL queries can be saved in stored procedures.SQL server are more
effiecient to run and more secure then SQL queries becaz stored procedures are
compiled.
 In Microsoft Access a stored procedure is called a parameter query.
Using stored procedures with a GridView Control:
In the following activity you need to have a local version of SQL server Express
running.
1. Right-click the ch10_GridView_DisplaySP.aspx page in the solution Explorer Window
and select the view in designer.
2. Click the <smart> tag to open the task List for the SqlDataSource2 and then select
configure Data Source.
3. Select ch10_ResidentialSQLConnectionString from the drop-down list. Do not select a
table.Instead, select the radio button labeled Specify a custom SQL statement or stored procedure. In
the drop down list, select ch10_Display_AllPropertiesByState as shown in fig 10-14.click next.

4. in the parameter source drop-down list,select control.in the control ID drop-down list,selec
DropDownList as shown I fig 10-15.click next and then click finish.

5. Click the source tab. Locate the code for the price Bound Field column. Insert the
DataFormatString and HtmlEncode properties as shown in fig 10-16.
Using stored procedures with a FormView control
Create the stored procedures to select and update the database. In fig 10-23 displays the insert,
delete, and update parameters that have been inserted for you.
Securing Databases:
 Securing databases
 Detecting Database Errors
Securing Databases:
 Hackers are people who intrude into another person’s software.
 Their intensions may be to expose, modify or delete the data or files on your network.SQL
injection is a technique that is used by hackers to attach SQL statements to an existing SQL
query in order to run additional commands.
Detecting Database Errors:
Detecting database errors-The Exception object contains information about the error, such as
the exception umber which helps you determine the type of error that occurred.
.
Unit-V
Evolution of c#

 The first release of C# (C# 1.0) was all about building a new language for managed code that
appealed, mostly, to C++ and Java programmers.
 The second release (C# 2.0) was mostly about adding what wasn’t time to built into
the 1.0release. The main feature for this release was Generics.
 The third release (C# 3.0) was all about reducing the impedance mismatch between general
purpose programming languages and databases. To achieve this goal, several functional
programming features were added to the language and LINQ was born.
 High level language came in late 1950s with FORTRAN(formula translator) and later
COBOL(Common Business oriented language).
 These language were considered as high level languages.because they were designed to the
accessible to humans - easy to read and write and close to English language.
 Some of the more note worthy high level programming language are C,C++
vb,java & now c#.
 C++ is an extension of c.which actually evolved from bcpl & bin 1973.
 C was developrd by dennis Ritchie at bell lab.
 Bjarne stroustrup is considered as the father of c++ for his design work in early 1980’s.
 C++ includes features of oops c++ is used heavily in computer industry today.
 Smalltask considered a pure ool was developed by Xerox palo alto research center(PARC).
 Visual basic,introduced in 1991 deriverd from BASIC(Beginners all purpose symbolic
instruction code) programming language developed in 1960s.
 VB easily creates the windows based graphical user interfaces(GUI)
 Java was introduced in 1995 and was originally called oak.
 Business community used for java most heavily for web applications.
 C# is one of the newest programming language. It is closely to c and c++ but many
developers consider it akin to java
 C# has GUI features of VB and added the power of C++ and object oriented class libraries
similar to java.
 C# can be used to develop any type of software components including mobile applications,
dynamic web pages, databases access components, web services and console based
application .Net
 .Net is an environment in which programs run and was designed to be a new programming
paradigm.
 It is not an operating system but rather a buyer between operating system & other
application.
 Officially announcement in 2000 .net was in development for over 3 years.
 Finally in feb2002 microsoft finally released the first version of visual stdio,the the IDE for
developing c# .net ,vb .net,visual c++.net visual j# .net & visual c#.net
 multilevel language Independent.
 .Net framework baseclasses.
 Dynamic web pages & web services->ADO.Net supports.

Going forward, new trends are showing up in the industry and modern programming languages need
to be more:
Declarative

 With imperative languages, although having the eye on the what, programs need to focus on
the how.
 This leads to over specification of the solution to the problem in hand, making next to
impossible to the execution engine to be smart about the execution of the program and
optimize it to run it more efficiently (given the hardware available, for example).
 Declarative languages, on the other hand, focus only on the what and leave the howto the
execution engine.
 LINQ made C# more declarative by using higher level constructs like orderby and group
by that give the execution engine a much better chance of optimizing the execution (by
parallelizing it, for example).

Concurrent

 Concurrency is hard and needs to be thought about and it’s very hard to shoehorn it into a
programming language. Parallel.For (from the parallel extensions) looks like a
parallel for because enough expressiveness has been built into C# 3.0 to allow this without
having to commit to specific language syntax.

Dynamic

 There was been lots of debate on which ones are the better programming
languages: static or dynamic.
 The fact is that both have good qualities and users of both types of languages want to have
it all.

 All these trends require a paradigm switch. C# is, in many ways, already a multi-paradigm
language.
 It’s still very object oriented (class oriented as some might say) but it can be argued that C#
3.0 has become a functional programming language because it has all the cornerstones of
what a functional programming language needs. Moving forward, it will have even more.
 Besides the influence of these trends, there was a decision of co-evolution of
the C# and Visual Basic programming languages.
 Since its inception, there has been some effort to position C# and Visual Basic against each
other and to try to explain what should be done with each language or what kind of
programmers use one or the other.
 Each language should be chosen based on past experience and familiarity of the
developer/team/project/company and not by particular features.
 In the past, every time a feature was added to one language, the users of the other wanted
that feature too.
 Going forward, when a feature is added to one language, the other will work hard to add the
same feature.
 This doesn’t mean that XML literals will be added to C# (because almost the same can be
achieved with LINQ To XML), but Visual Basicwill have auto-implemented properties.
 Most of these features require or are built on top of features of the .NET Framework and, the
focus for C# 4.0 was on dynamic programming, not just dynamic types but being able to talk
with anything that isn’t a .NET class.
 Also introduced in C# 4.0 is co-variance and contra-variance for
generic interfaces and delegates.
C# Relates to .NET Framework
 C# has a special relationship to its runtime environment,the .NET Framework.
 The reason for this is twofold.
o C# was initially designed by Microsoft to create code for the .NET Framework.
o The libraries used by C# are the ones defined by the .NET Framework.

WHY C#
 C#,Pronounced c sharp,is a computer language used to give instructions that tell the
computer what to do,how to do it,and when to do it.
 The Microsoft .NET Framework is a library of objects that create or draw things on the
computer.
 The C# language is used to create applications that display on a black window referred to
as the DOS prompt or DOS window.

 C# is a true OOL that includes a rich set of instruction statements.


 C# was the language used for development of much of .Net, the new Microsoft
programming paradigm the includes more than 2000 predefined classess that make up of
FCL(frame work class library)

 C# also use web standards,HTML,XML,SOAP(Simple object Access Protocols).


 C# has GUI features of VB, and added the power of c++ and has object oriented class
librarys similar to java.
 C++ -> ANSI -> American National Standard Institute,
 c# ->(ECMA) -> European computer manufacture association and its common language
infrastructure(CLI) specification into international standards.
 Platform Independent : First it is developed to run only windows platform. But nowdays
it is possible to run Linux platform also.
 C# program can also access the databases such as Access, SQL server using Data source
Configuration tools.

ELEMENTS OF C# PROGRAM
 There are basic elements that all C# executable programs with a simple c# program.

 Comments

 Using Directive

 Namespace

 Class definition

 Main Method

 Method Body- Statements

Comments:
 Writing comment is like making notes for yourself or for readers of your program.
 Comments are not considered as a instruction to the computer.

Eg:
//This is first program
This 2 forward slashes used to indicate comment a single line.
Comments serve 2 functions
*They make the code more readable.
*They internally,document,what the program statement are doing.
In c#, there are 3 types of commenting syntax
1.Inline comments
2.Multiline comments
3.XML Document comments

1. Inline comments:

\\ first program
*Single line comment is said to be Inline comment.
*An Inline comments is indicated by two forward slashes. It is ignored by the compiler.
2. Multiline comments:
*Used for longer comments.
*A forward slash followed by an asterisk /* marks the beginning of a multiline comment and */
marks at the end.
Eg:
/* This is first line at the end of the program */
XML Document comment
*Uses 3 forward slashes///
*This is advanced documentation technique used for xml style comments.
Using Directive
 Used to permits the use of classes found in particular namespace.

Eg:
Using system;
Where “system” is a namespace.
 .Net provides more then 2000 classes that make up FCL.Used to reuse the code.

 In .Net forward dot(.) is used as a delimeter between classes & namespace.

Eg:
Using system.console;
Most frequently used namespace is system
Console.writeline(“Hellow world”)
(or)
NameSpace
Namespace firstprogram
{
Stmts;
}
Class definition
 C# Language,so everything is designed around a class,which is a building block of oop.

 C# doesn’t allow anything to be defined outside of a class.

 Every program must have atleast one class.


Class classname
{
Stmts;
}
Main Method:
Static void main()
{
Body of the method;
}
*This is the “entry point” for all application.
*A method is a collection of one or more statements combined to perform an action.
*Methods are similar to c++ function.
*The heading for the method contain its signature,which includes the name of the methods& its
argument lists.
Method Body-Statements:
 The body of the main() method consists of a single (or) multiline statement.

Eg:
Static void main()
{
Console.write(“Hellow”);
Console.write(“ “);
Console.write(“world!”);
)
o/p:
Hellow world!
*Here Main() is call another method name “write”
*A Method call is the same as Method invocation.Like main(),writeline() has a signature.
*The heading along with the body of the method is the definition on the Method.
Escape sequence:
/n -> next line
/t ->horizontal tab
/” -> double quotes
/’ -> single quotes
// ->Back slash
PROGRAMMING EXAMPLE
[C#]
Public static boolIsLocallpAddress(string host)
{
Try
{// get host IP addresses
IP Address[] hostIPs=Dns.GetHostAddresses(Dns.GetHostName());
//test if any host IP equals to any local IP or to localhost
Foreach(IPAddresshostIP in hostIPs)
{
//is localhost
If(IPAddress.IsLoopback(hostIP)) return true;
//is local address
Foreach(IP Address localIP in localIPs
{
If(hostIP.Equals(localIP)) return true;
}
}
}
Catch{}
Return false;
}

DATA TYPES AND EXPRESSIONS


DATA TYPES
 Data Types in a programming language describes that what type of data a variable can
hold.
 CSharp is a strongly typed language ,therefore every variable and object must have a
declared type.
 They are value Types,Reference Types and Pointer Types.
 In CSharp it possible to convert a value of one type into a value of another type.

Syntax:
DataType VariableName
DataType: The type of data that the variable can hold
VariableName: The variable we declare for hold the values.
EXAMPLE:
Int count;
Int:is the data type
Count: is the variable name
BOOL
 It is used to declare variable to store the Boolean values, true and false.
 In C#, there is no conversion between the bool type and other types.

C# Runtime type: System.Boolean


INT
 Int variables are stored signed 32 bit integer values in the range of -2,147,483,648 to
+2,147,483,647
C# Runtime type: System.Int32
int count
count=100;
Decimal
 The decimal keyword denotes a 128-bit data type.

C# Runtime type: System.Decimal


CSharpdeclaration:decimalval;
CSharpInitialization:val=0.12;
CSharp default Initialization value:0.0M
String
 The string type represents a string of Unicode characters. String variables are stored any
number of alphabetic, numerical, and special characters.

C# Runtime type: System.string


CSharpdeclaration:stringstr;
CSharpInitialization:val=str=”csharp string”

MAKKING DECISION
 The familiar if-then of visual basic,pascal and fortran has its analog in c#
if(y>0)
Z=x/y;
 Paranthesis around the condition are required in c#.if you want to have several statements as part
of the condition.you must enclose them in braces:
If(y>0)
{
z=x/y;
Console.riteline(“z=”+z);
}
 If you want to carry out either one set of statements or another depending on a single
condition,you should use the else clause along with the if statement.
If (y>0)
Z=x/y;
Else
Z=0;
 And if the else clause contains multiple statements,they must be enclosed in braces,as in the
code above.there are two types of styles for braces:
If(y>0)
{
Z=x/y;
}
 The other style, the if statement and the ending brace directly under the if:
If(y>0)
{
Z=x/y;
Console.writeline(“z=”+z);
}

Using system;

1. Name space consoleapplication1


{
Class program
{
Static void main(string[] args)
{
int number;

console.writeline(please enter a number between 0 and 10:”);


number=int.parse(console.readline());

if(number>10)
console.writeline(“hey! The number should be 10 or less!”);

else
if(number<0)
console.writeline(“hey! The number should be 0 or more!”);
else
console.writeline(Good job!”);
console.Readline();
}
}
}

Comparison Operators
 Above, we used the > operator to mean “greater than.” Most of these operators are the same in
C# as they are in C and other languages.
 Note particularly that “is equal to” requires two equal signs and that “not equal” is different than
in FORTRAN or VB.

> greater than


< less than
== is equal to
!= is not equal to
>= greater than or equal to
<= less than or equal to
Table 1: Comparison Operators in C#

Combining Conditions
 When you need to combine two or more conditions in a single if or other logical statement,
you use the symbols for the logical and, or, and not operators. These are totally different than
any other languages except C/C++ and are confusingly like the bitwise operators shown in
Table 2.

&& logical And


|| logical Or
~ logical Not
Table 2 Boolean operators in C#

So, while in VB.Net we would write:


If ( 0 < x) And (x <= 24) Then
Console.writeLine (“Time is up”)
in C# we would write:
if ( (0 < x) && ( x <= 24) )
Console.writeLine(“Time is up”);
If statement:
*One way if statement
Syntax
If(expression)
{
Statement;
}
Eg:
If(5>0)
{
Console.write(“positive no”);
}
Two way if statement:
If(expression)
{
Stmt;
}
Else
{
Stmt;
}
Eg:
If(a>b)
{
Console.writeline(“A is greater”);
}
Else
{
Console.writeline(“B is greater”);
}
Nested If…..else statement:
If(expression)
{
Stmt;
}
Else if (expression)
{
Stmt;
}
Else
{
Stmt;
}
Switch selection stmt:
 Multiple selection structure.

syntax
Switch(expression)
{
Case value1:stmt;
Break;
Case value2:stmt;
Break;
Case value n:stmt;
Break;
Default: stmt;
Break;
}

Eg:
Switch(weekday)
{
Case 1: console.writeline(“Mon”);
Break:
Case 2:Console.writeline(“tue”);
Break;
Case 3: console.writeliine(“wed”);
Break;
}

REPEATING INSTRUCTIONS
 WHILE STATEMENT
 FOR STATEMENT
 SWITCH STATEMENT
 DO/WHILE STATEMENT
While Statement
 A repetition structure allows the programmer to specify that an action is to be repeated while
a condition remains true.
Syntax:
while (expression) statement

Example
Int product =2;
While(product<=1000)
Product =2* product;
For Statement
 The for repetition structure handles the details of counter-controlled repetition.

Syntax:
for(initialization; condition; step)

statement

initialization : Initialize the value of variable.


condition : Evaluate the condition

step : Step taken for each execution of loop body

Example
Using System;
Class ForCounter
{
Static void Main(string[]args)
{
for(int counter=1;counter<=5;counter++)
Console.WriteLine(counter);
}
}
Switch Multiple-Selection Structure
 C# provides the switch multiple-selection structure to handle such decision making.

Syntax:
switch (expression)
{
case constant-expression:
statement(s);
jump-statement
[default: statement(s);]

Example
switch(grade)
{
case’A’:
case’a’:
++aCount ;
Break;
case’B’:
case’b’:
++bCount ;
Break;
default:
Console.Writeln(“Incorrect letter grade entered,”+”\nGrade not added to totals.”);
Break;
}

Do/While Statement
 The do/while structure tests the loop-continuation condition after the loop body
executes.Therefore,the loop body always excutes at least once.
 When a do/while structure terminates,execution continues with the statement after the while
cause.
Syntax:
Do
{
Statements
} while (condition);

Example
Using System;
Class MainClass
{
Public static void main()
{
int n=0;
do
{
Console.WriteLine(“Number is {0}”,n);
n++;
}
While (n<10);
}
}
}
Output:
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10

ARRAYS:-

 C# arrays are zero indexed.


 That is, the array indexes start at zero.
 Arrays in C# work similarly to how arrays work in most other popular languages.
 There are a few differences that you should be aware of.
 When declaring an array, the square brackets ([]) must come after the type, not the
identifier.
 Placing the brackets after the identifier is not legal syntax in C#.

int[] table; // not int table[];

 Another detail is that the size of the array is not part of its type as it is in the C
language.
 This allows you to declare an array and assign any array of int objects to it, regardless
of the array's length.

int[] numbers; // declare numbers as an int array of any size


numbers = new int[10]; // numbers is a 10-element array
numbers = new int[20]; // now it's a 20-element array

DECLARING ARRAYS:-

 C# supports single-dimensional arrays,


 multidimensional arrays (rectangular arrays), and
 array-of-arrays (jagged arrays).
 The following examples show how to declare different kinds of arrays:

SINGLE-DIMENSIONAL ARRAYS:
int[] numbers;

MULTIDIMENSIONAL ARRAYS:

string[,] names;

ARRAY-OF-ARRAYS (JAGGED):

byte[][] scores;

 Declaring them (as shown above) does not actually create the arrays.
 In C#, arrays are objects (discussed later in this tutorial) and must be instantiated.
 The following examples show how to create arrays:

SINGLE-DIMENSIONAL ARRAYS:

int[] numbers = new int[5];

MULTIDIMENSIONAL ARRAYS:

string[,] names = new string[5,4];

ARRAY-OF-ARRAYS (JAGGED):

byte[][] scores = new byte[5][];


for (int x = 0; x <scores.Length; x++)
{
scores[x] = new byte[4];
}

 You can also have larger arrays. For example, you can have a three-dimensional rectangular
array:

int[,,] buttons = new int[4,5,3];

 You can even mix rectangular and jagged arrays. For example, the following code declares a
single-dimensional array of three-dimensional arrays of two-dimensional arrays of type int:

int[][,,][,] numbers;

Example

The following is a complete C# program that declares and instantiates arrays as discussed above.

// arrays.cs
using System;
classDeclareArraysSample
{
public static void Main()
{
// Single-dimensional array
int[] numbers = new int[5];

// Multidimensional array
string[,] names = new string[5,4];

// Array-of-arrays (jagged array)


byte[][] scores = new byte[5][];

// Create the jagged array


for (int i = 0; i <scores.Length; i++)
{
scores[i] = new byte[i+3];
}

// Print length of each row


for (int i = 0; i <scores.Length; i++)
{
Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length);
}
}
}

Output

Copy
Length of row 0 is 3
Length of row 1 is 4
Length of row 2 is 5
Length of row 3 is 6
Length of row 4 is 7

INITIALIZING ARRAYS:-

 C# provides simple and straightforward ways to initialize arrays at declaration time by


enclosing the initial values in curly braces ({}).
 The following examples show different ways to initialize different kinds of arrays.

Note : If you do not initialize an array at the time of declaration, the array members are
automatically initialized to the default initial value for the array type. Also, if you declare the array
as a field of a type, it will be set to the default value null when you instantiate the type.

SINGLE-DIMENSIONAL ARRAY:-

int[] numbers = new int[5] {1, 2, 3, 4, 5};


string[] names = new string[3] {"Matt", "Joanne", "Robert"};

You can omit the size of the array, like this:


int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {"Matt", "Joanne", "Robert"};

You can also omit the newoperator if an initializer is provided, like this:

int[] numbers = {1, 2, 3, 4, 5};


string[] names = {"Matt", "Joanne", "Robert"};

MULTIDIMENSIONAL ARRAY:-

int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };


string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} };

You can omit the size of the array, like this:

int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };


string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Albert"} };

You can also omit the newoperator if an initializer is provided, like this:

int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };


string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} };

JAGGED ARRAY (ARRAY-OF-ARRAYS):-

You can initialize jagged arrays like this example:

int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

You can also omit the size of the first array, like this:

int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

-or-

int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

Notice that there is no initialization syntax for the elements of a jagged array.

ACCESSING ARRAY MEMBERS:-

 Accessing array members is straightforward and similar to how you access array
members in C/C++.
 For example, the following code creates an array called numbers and then assigns a 5
to the fifth element of the array:

int[] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};


numbers[4] = 5;

 The following code declares a multidimensional array and assigns 5 to the member
located at [1, 1]:
int[,] numbers = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };
numbers[1, 1] = 5;

 The following is a declaration of a single-dimension jagged array that contains two


elements.
 The first element is an array of two integers, and the second is an array of three
integers:

int[][] numbers = new int[][] { new int[] {1, 2}, new int[] {3, 4, 5} };

 The following statements assign 58 to the first element of the first array and 667 to the
second element of the second array:

numbers[0][0] = 58;
numbers[1][1] = 667;

ARRAYS ARE OBJECTS:-

 In C#, arrays are actually objects.


 System.Array is the abstract base type of all array types.
 You can use the properties, and other class members, that System.Array has.
 An example of this would be using the Lengthproperty to get the length of an array.
 The following code assigns the length of the numbers array, which is 5, to a variable
called LengthOfNumbers:

int[] numbers = {1, 2, 3, 4, 5};


intLengthOfNumbers = numbers.Length;

 The System.Array class provides many other useful methods/properties, such as


methods for sorting, searching, and copying arrays.

USING FOR EACH ON ARRAYS:-

 C# also provides the foreach statement.


 This statement provides a simple, clean way to iterate through the elements of an array.
 For example, the following code creates an array called numbers and iterates through it
with the foreach statement:

int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};


foreach (int i in numbers)
{
System.Console.WriteLine(i);
}

 With multidimensional arrays, you can use the same method to iterate through the
elements, for example:
 int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}};
foreach(int i in numbers)
{
Console.Write("{0} ", i);
}
The output of this example is:

9 99 3 33 5 55

However, with multidimensional arrays, using a nested for loop gives you more control over the
array elements

COLLECTIONS:-

ARRAYLIST:-

 ArrayList is one of the most flexible data structure from CSharp Collections.
 ArrayList contains a simple list of values
 ArrayList implements the IList interface using an array and very easily we can add ,
insert , delete , view etc.
 It is very flexible because we can add without any size information , that is it will grow
dynamically and also shrink .

Add : Add an Item in an ArrayList


Insert : Insert an Item in a specified position in an ArrayList
Remove : Remove an Item from ArrayList
RemoveAt: remove an item from a specified position

Sort : Sort Items in an ArrayList

add an Item in an ArrayList

Syntax :
ArrayList.add(object)
object : The Item to be add the ArrayList
ArrayListarr;

Eg: arr.Add("Item1");

Insert an Item in an ArrayList

Syntax :
ArrayList.insert(index,object)
index : The position of the item in an ArrayList
object : The Item to be add the ArrayList
ArrayListarr;

Eg: arr.Insert(3, "Item3");

remove an item from arrayList

Syntax :
ArrayList.Remove(object)
object : The Item to be add the ArrayList

Eg: arr.Remove("item2")

remove an item in a specified position from an ArrayList

Syntax :
ArrayList.RemoveAt(index)
index : the position of an item to remove from an ArrayList

Eg: ItemList.RemoveAt(2)

sortArrayList

Syntax : ArrayList.Sort()

The following CSharp source code shows some function in ArrayList

Eg program:-
using System;
usingSystem.Collections;
usingSystem.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
ArrayListItemList = new ArrayList();
ItemList.Add("Item4");
ItemList.Add("Item5");
ItemList.Add("Item2");
ItemList.Add("Item1");
ItemList.Add("Item3");
MessageBox.Show ("Shows Added Items");
for (i = 0; i < = ItemList.Count - 1; i++)
{
MessageBox.Show(ItemList[i].ToString());
}
//insert an item
ItemList.Insert(3, "Item6");
//sort itemms in an arraylist
ItemList.Sort();
//remove an item
ItemList.Remove("Item1");
//remove item from a specified index
ItemList.RemoveAt(3);
MessageBox.Show("Shows final Items the ArrayList");
for (i = 0; i < = ItemList.Count - 1; i++)
{
MessageBox.Show(ItemList[i].ToString());
}
}
}
}
 when you execute this C# program , at first add five items in the arraylist and displays.
 Then again one more item inserted in the third position , and then sort all items.
 Next it remove the item1 and also remove the item in the third position . Finally it shows the
existing items.

HASHTABLE:-
 In C# represents a collection of key/value pairs which maps keys to value.
 Any non-null object can be used as a key but a value can.
 We can retrieve items from hashTable to provide the key .
 Both keys and values are Objects.
 The commonly used functions in Hashtable are :

Add : To add a pair of value in HashTable


ContainsKey : Check if a specified key exist or not
ContainsValue : Check the specified Value exist in HashTable
Remove : Remove the specified Key and corresponding Value

Add : To add a pair of value in HashTable

Syntax : HashTable.Add(Key,Value)
Key : The Key value
Value : The value of corresponding key
Hashtableht;

ht.Add("1", "Sunday");

ContainsKey : Check if a specified key exist or not

Synatx : boolHashTable.ContainsKey(key)
Key : The Key value for search in HahTable
Returns : return true if item exist else false

ht.Contains("1");

ContainsValue : Check the specified Value exist in HashTable

Synatx : boolHashTable.ContainsValue(Value)
Value : Search the specified Value in HashTable
Returns : return true if item exist else false

ht.ContainsValue("Sunday")

Remove : Remove the specified Key and corresponding Value


Syntax : HashTable.Remove(Key)
Key : The key of the element to remove

ht.Remove("1");

The following source code shows some important operations in a HashTable

using System;
usingSystem.Collections;
usingSystem.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Hashtable weeks = new Hashtable();
weeks.Add("1", "SunDay");
weeks.Add("2", "MonDay");
weeks.Add("3", "TueDay");
weeks.Add("4", "WedDay");
weeks.Add("5", "ThuDay");
weeks.Add("6", "FriDay");
weeks.Add("7", "SatDay");
//Display a single Item
MessageBox.Show(weeks["5"].ToString ());
//Search an Item
if (weeks.ContainsValue("TueDay"))
{
MessageBox.Show("Find");
}
else
{
MessageBox.Show("Not find");
}
//remove an Item
weeks.Remove("3");
//Display all key value pairs
foreach (DictionaryEntry day in weeks )
{
MessageBox.Show (day.Key + " - " + day.Value );
}
}
}
}
 When you execute this C# program it will add seven entries in the hashtable.
 The first message it will display the item 5.

 Then it check the value "TueDay" is existing or not .

 Next it remove the third item from HashTable.

 Finaly it displays all items exist in the HashTable.

PROGRAMMING BASED ON EVENTS


 An event in c# is a way for a class to provide notifications to clients of that class when some
interesting thing happens to an object.

 Events, however, need not be used only for graphical interfaces.

 Events provide a generally useful way for object to signal state changes that may be useful to
clients of that objects.

 Events are an important building block for creating classes that can be reused in large
number of different programs.

 An event is a way for a class to allow clients to give it delegates to methods that should be
called when the event occurs.

 When the event occurs, the delegates given to it by its clients are invoked.

 Listbox controls object


 Combobox control object
 Menustrip Comtrol Object
 Checkbox Object
 Radiobutton Object
Menustrip Comtrol Object
 Menus offer advantage of taking up minimal space on your window
 They enables you to add more functionality to your application
 Selecting the Menu strip object enables using the Properties windows
 To add the text for the menu option selection the menustrip icons &click in the upper –left
corner of the form

New :

private void newToolStripMenuItem_Click(object sender, EventArgs e)

{
richTextBox1.Text = "";
}
Open :
-------
private void openToolStripMenuItem_Click(object sender, EventArgs e)

{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(openFileDialog1.FileName,
RichTextBoxStreamType.PlainText);
}
}

Save : -

private void saveToolStripMenuItem_Click(object sender, EventArgs e)


{
saveFileDialog1.Filter = "Textfile|*.txt|All Files|*.*";

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(saveFileDialog1.FileName ,
RichTextBoxStreamType.PlainText);
}
}
Exit :
------
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
Cut :
-----
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Cut();
}
Copy :
--------
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Copy();
}
Paste : --------

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)


{
richTextBox1.Paste();
}
Select All :
-------------

private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)


{

richTextBox1.SelectAll();
}
Font : -------

private void fontTypeToolStripMenuItem_Click(object sender, EventArgs e)


{
if (fontDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.Font = fontDialog1.Font ;
}
}
Color :
---------

private void fontColorToolStripMenuItem_Click(object sender, EventArgs e)


{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.ForeColor = colorDialog1.Color ;
}
}

Short Cut Icons:-


Addnew:-
------------
private void toolStripButton1_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
toolStripStatusLabel1.Text = "New file opened";
}

Open:-
--------
private void toolStripButton2_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(openFileDialog1.FileName,
RichTextBoxStreamType.PlainText);
}
toolStripStatusLabel1.Text = "file opened";
}
Paste:-
---------
private void toolStripButton3_Click(object sender, EventArgs e)
{
richTextBox1.Paste();
}

Save:-
-------
private void toolStripButton4_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "Textfile|*.txt|All Files|*.*";

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{

richTextBox1.SaveFile(saveFileDialog1.FileName,
RichTextBoxStreamType.PlainText);
}
toolStripStatusLabel1.Text = "File Saved";
}
Copy:-
--------
private void toolStripButton6_Click(object sender, EventArgs e)
{
richTextBox1.Copy();
}
Copy:-
---------
private void toolStripButton5_Click(object sender, EventArgs e)
{
richTextBox1.Cut();
}
}
}
Menus Output:-
New:

Open :
Save :

Cut :
DATABASE ACCESS WITH ADO.NET
 ADO.NET is a set of classes that expose data access services to the .NET programmer.
 ADO.NET provides a rich set of components for creating distributed, data-sharing
applications.
 It is an integral part of the .NET Framework, providing access to relational data, XML, and
application data. ADO.NET supports a variety of development needs, including the
creation of front-end database clients and middle-tier business objects used by
applications, tools, languages, or Internet browsers.
 To Use the ADO classes we need to include the ADO.NET namespace and a few handy date
classes.
 ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as well
as data sources exposed through OLE DB and XML.
 Data-sharing consumer applications can use ADO.NET to connect to these data sources and
retrieve, manipulate, and update data.

 The ADO.NET classes are found in System.Data.dll, and are integrated with the XML
classes found in System.Xml.dll. When compiling code that uses
the System.Data namespace, reference both System.Data.dll and System.Xml.dll. For an
example of compiling an ADO.NET application using a command line compiler,
see ADO.NET Sample Application.
 ADO.NET provides functionality to developers writing managed code similar to the
functionality provided to native COM developers by ADO.
 ADO.NET provides data access services in the Microsoft .NET platform.

You can use ADO.NET to access data by using the new .NET Framework data providers which are:

 Data Provider for SQL Server (System.Data.SqlClient).


 Data Provider for OLEDB (System.Data.OleDb).
 Data Provider for ODBC (System.Data.Odbc).
 Data Provider for Oracle (System.Data.OracleClient).
ADO.NET is a set of classes that expose data access services to the .NET developer. The ADO.NET classes are ound
inSystem.Data.dll and are integrated with the XML classes in System.Xml.dll.


 There are two central components of ADO.NET classes: the DataSet, and
the .NET Framework Data Provider.

Data Provider is a set of components including:

 the Connection object


(SqlConnection, OleDbConnection, OdbcConnection, OracleConnection)

 the Command object (SqlCommand, OleDbCommand, OdbcCommand, OracleCommand)

 the DataReader object


(SqlDataReader, OleDbDataReader, OdbcDataReader, OracleDataReader)and
 the DataAdapter object
(SqlDataAdapter, OleDbDataAdapter, OdbcDataAdapter,OracleDataAdapter).

 DataSet object represents a disconnected cache of data which is made up of DataTables


and DataRelations that represent the result of the command.

ADO.NET Object Model

UsingSystem.Data;
usingSystem.data;ADO
usingSystem.globalization;
publicconst string DB_CONN_STRING=“Driver={Mocrosoft Access Driver(*.mdb)};”+
“DBQ=D:\\CS\\TrstDbReadWrite\\SimpleTest.mdb”;
Reading data
 Reading is done using the ADODataReaderclass.the steps to perform the read are;

We open the database with an ADOConnection.


We open the database with an ADOConnection.
ADOConnection conn=new ADOConnection(DB_CONN_STRING);
Conn.open();
 We create a SQL statement to define the data to be retrived.This commend is executed to
return an ADODataReader object.

ADODataReaderdr;
ADOCommandcmd=new ADOCommend(“SELECT*FROM person”,conn);
Cmd.Execute(out dr);
We loop through each record in the ADODataReader until we are done.
While(dr.Read() )
{
System.console.WriteLine(dr[“firstName”]);
}
Insert,Modify,Delete and other SQL commands
 Inserting,Modifying and Deleting can very simply be done using SQL statements.the
following code performs a SQL commend to insert a record.

Strings SQLCommand=”INSERT INTO Person(Age,FirstName, Description,Updated)”+


“VALUES(55,’Bob’,Is a Penguin’,’2001/12/25 20:30:15’);”;
ADOCommandcmdAdder=new ADOCommand(sSQLCommand,DB_CONN_STRING);
cmdAdder.ActiveConnection.open();
intnNoAdded=cmdAdder.executeNonQuery();
System.console.writeLine(“\nRow(s) Added=+nNoAdded+”\n”);
Inserting
The above code inserted a record by building a SQL command which was later executed.
 Numerical values are presented directly.No single quotes(‘).

 Strings are presented wrapped in single quotes(‘blah’)

 Be sure the strings do not include any embedded single or double quotes.

 Date and times are presented wrapped in single quotes in international


format(‘YYYYY/MM/DDHH:MM:SS’).

Modifying
 The UPDATE command indicates the records to be modified and the modification to be
made.

 The return value of the ExecuteNonQuery() indicates the number of records changes.

String sSQLCommand=”UPDATE Person SET Age=27 WHERE FirstName=’Peter”’;


Deleting
 The DELETE command indicates the records to be deleted.

String sSQLCommand=”DELETE FROM Person WHERE firstName=’Bobo”’;

You might also like