Professional Documents
Culture Documents
Net
NET Framework
The .NET Framework is the infrastructure for the new Microsoft .NET Platform.
The .NET Framework is a common environment for building, deploying, and running Web
Services and Web Applications.
The .NET Framework contains common class libraries - like ADO.NET, ASP.NET and Windows
Forms - to provide advanced standard services that can be integrated into a variety of computer
systems.
The .NET Framework is language neutral. Currently it supports C++, C#, Visual Basic, JScript
(The Microsoft version of JavaScript) and COBOL. Third-party languages - like Eiffel, Perl,
Python, Smalltalk, and others - will also be available for building future .NET Framework
applications.
The new Visual Studio.NET is a common development environment for the new .NET
Framework. It provides a feature-rich application execution environment, simplified development
and easy integration between a number of different development languages.
Common Language Run Time ( CLR)
Compilers and tools expose the runtime's functionality and enable you to write code that benefits
from this managed execution environment. Code that you develop with a language compiler that
targets the runtime is called managed code; it benefits from features such as cross-language
integration, cross-language exception handling, enhanced security, versioning and deployment
support, a simplified model for component interaction, and debugging and profiling services.
To enable the runtime to provide services to managed code, language compilers must emit
metadata that describes the types, members, and references in your code. Metadata is stored with
the code; every loadable common language runtime portable executable (PE) file contains
metadata. The runtime uses metadata to locate and load classes, lay out instances in memory,
resolve method invocations, generate native code, enforce security, and set run-time context
boundaries.
The runtime automatically handles object layout and manages references to objects, releasing
them when they are no longer being used. Objects whose lifetimes are managed in this way are
called managed data. Garbage collection eliminates memory leaks as well as some other common
programming errors. If your code is managed, you can use managed data, unmanaged data, or
both managed and unmanaged data in your .NET Framework application. Because language
compilers supply their own types, such as primitive types, you might not always know (or need to
know) whether your data is being managed.
The common language runtime makes it easy to design components and applications whose
objects interact across languages. Objects written in different languages can communicate with
each other, and their behaviors can be tightly integrated. For example, you can define a class and
then use a different language to derive a class from your original class or call a method on the
original class. You can also pass an instance of a class to a method of a class written in a different
language. This cross-language integration is possible because language compilers and tools that
target the runtime use a common type system defined by the runtime, and they follow the
runtime's rules for defining new types, as well as for creating, using, persisting, and binding to
types.
As part of their metadata, all managed components carry information about the components and
resources they were built against. The runtime uses this information to ensure that your
component or application has the specified versions of everything it needs, which makes your
code less likely to break because of some unmet dependency. Registration information and state
data are no longer stored in the registry where they can be difficult to establish and maintain.
Rather, information about the types you define (and their dependencies) is stored with the code as
metadata, making the tasks of component replication and removal much less complicated.
Language compilers and tools expose the runtime's functionality in ways that are intended to be
useful and intuitive to developers. This means that some features of the runtime might be more
noticeable in one environment than in another. How you experience the runtime depends on
which language compilers or tools you use. For example, if you are a Visual Basic developer, you
might notice that with the common language runtime, the Visual Basic language has more object-
oriented features than before. Following are some benefits of the runtime:
• Performance improvements.
• The ability to easily use components developed in other languages.
• Extensible types provided by a class library.
• New language features such as inheritance, interfaces, and overloading for object-oriented
programming; support for explicit free threading that allows creation of multithreaded,
scalable applications; support for structured exception handling and custom attributes.
If you use Microsoft Visual C++.NET, you can write managed code using the Managed
Extensions for C++, which provide the benefits of a managed execution environment as well as
access to powerful capabilities and expressive data types that you are familiar with. Additional
runtime features include:
Common Type System (CTS) describes how types are declared, used and managed in the
runtime and facilitates cross-language integration, type safety, and high performance code
execution.
The CLS is simply a specification that defines the rules to support language integration in such a
way that programs written in any language, yet can interoperate with one another, taking full
advantage of inheritance, polymorphism, exceptions, and other features.
ASP.NET
ASP.NET is the latest version of ASP. It includes Web Services to link applications, services and
devices using HTTP, HTML, XML and SOAP.
New in ASP.NET:
Visual Basic.NET
C#
C# is a new computer programming language developed by Microsoft Corporation, USA.
C# is a fully object – oriented language like JAVA. It has been developed to support the key
features of .Net framework.
SQL Server 2000
SQL Server 2000 has strong support for XML and HTTP which are two of the main
infrastructure technologies for .NET.
Some of the most important new SQL Server features are direct access to the database from a
browser, query of relational data with results returned as XML, as well as storage of XML in
relational formats.
Internet Information Services 6.0
IIS 6.0 has strong support for more programming to take place on the server, to allow the new
Web Applications to run in any browser on any platform.
What are Web Services?
Web services make it easier to communicate between different applications. They also make it
possible for developers to reuse existing web services instead of writing new ones.
Web services can create new possibilities for many businesses because it provides an easy way to
distribute information to a large number of consumers. One example could be flight schedules
and ticket reservation systems.
C Sharp
C# is a new computer programming language developed by Microsoft Corporation, USA.
C# is a fully object – oriented language like JAVA. It has been developed to support the key
features of .Net framework.
It is a simple, efficient, productive and type-safe language derived from popular C and
C++ languages. Although it belongs to the family of C / C++ , it is a purely object oriented,
modern language suitable for developing web based applications.
Major Features
Applications of C#
1) Console application
2) Windows application
3) Developing windows controls
4) Developing ASP.Net projects
5) Creating Web Controls
6) Providing web services
1) Macros
2) Multiple Inheritance
3) Templates
4) Pointers
5) Global Variables
6) Typedef statement
7) Default Arguments
8) Constant member functions or parameters
9) Forward declaration of classes
Enhancements to C++
Characteristics of C#
• Simple
• Consistent
• Modern
• Object-oriented
• Type-safe
Simple
Consistent
C# supports a unified type system which eliminates the problem of varying of integer
types. All types are treated as objects and developers can extend the type system simply and
easily.
Modern
Object – oriented
C# is truly object oriented. It supports all the three tenets of object oriented systems,
namely
• Encapsulation
• Inheritance and
• Polymorphism
The entire c# class model is built on top of the Virtual Object System (VOS) of the .Net
Framework. In c#, everything is an object.
Type-Safe
Let's begin in the traditional way, by looking at the code of a Hello World program
using System;
Console.WriteLine("Hello World!");
The first thing to note about C# is that it is case-sensitive. You will therefore get compiler errors
if, for instance, you write 'console' rather than 'Console'. The second thing to note is that every
statement finishes with a semicolon (;) or else takes a code block within curly braces.
Class Declaration:
C# is a true object oriented language and therefore everything must be placed inside a class. Class
is a keyword and declares a new class definition.
The Braces:
C# is a block-structured language, meaning code blocks are always enclosed by braces { and }.
define a method named Main. Every C# executable program must include the Main method in
one of the classes. This is the starting point for the execution of the program. A C# application
can have any number of classes but ‘only one’ class can have the Main method to initiate the
execution.
public – is a access modifier that tells the C# compiler that the main method is accessible by
anyone.
static – the keyword static declares that the Main method is a global one and can be called
without creating an instance of the class.
void - is a type modifier that states the Main method does not return any value.
using System;
class Sample
C# is a type-safe language. Variables are declared as being of a particular type, and each variable
is constrained to hold only values of its declared type. Variables can hold either value types or
reference types, or they can be pointers.
Here's a quick recap of the difference between value types and reference types.
- where a variable v contains a value type, it directly contains an object with some value. No other
variable v' can directly contain the object contained by v (although v' might contain an object
with the same value).
- where a variable v contains a reference type, what it directly contains is something which refers
to an object. Another variable v' can contain a reference to the same object refered to by v.
Value Types
It is possible in C# to define your own value types by declaring enumerations or structs. These
user-defined types are mostly treated in exactly the same way as C#'s predefined value types,
although compilers are optimised for the latter. The following table lists, and gives information
about, the predefined value types. Because in C# all of the apparently fundamental value types
are in fact built up from the (actually fundamental) object type, the list also indicates which
System types in the .Net framework correspond to these pre-defined types.
In the following lines of code, two variables are declared and set with integer values.
int x = 10;
int y = x;
y = 20; // after this statement x holds value 10 and y holds value 20
Reference Types
The pre-defined reference types are object and string, where object - as we have mentioned above
- is the ultimate base class of all other types. New reference types can be defined using 'class',
'interface', and 'delegate' declarations.
Reference types actually hold the value of a memory address occupied by the object they
reference. Consider the following piece of code, in which two variables are given a reference to
the same object (for the sake of the example, this object is taken to contain the numeric property
'myValue').
object x = new object();
x.myValue = 10;
object y = x;
y.myValue = 20; // after this statement both x.myValue and y.myValue equal 20
This code illustrates how changing a property of an object using a particular reference to it is
reflected in all other references to it. Note, however, that although strings are reference types,
they work rather more like value types. When one string is set to the value of another, eg
string s1 = "hello";
string s2 = s1;
Then s2 does at this point reference the same string object as s1. However, when the value of s1
is changed, for instance with
s1 = "goodbye";
what happens is that a new string object is created for s1 to point to. Hence, following this piece
of code, s1 equals "goodbye", whereas s2 still equals "hello".
The reason for this behavior is that string objects are 'immutable'. That is, the properties of these
objects can't themselves change. So in order to change what a string variable references, a new
string object must be created.
Boxing
C# allows you convert any value type to a corresponding reference type, and to convert the
resultant 'boxed' type back again. The following piece of code demonstrates boxing. When the
second line executes, an object is initiated as the value of 'box', and the value held by i is copied
across to this object. It is interesting to note that the runtime type of box is returned as the boxed
value type; the 'is' operator thus returns the type of box below as 'int'.
int i = 123;
object box = i;
if (box is int)
{Console.Write("Box contains an int");} // this line is printed
Unboxing
Unboxing is the process of converting the object type back to the value type. Remember that we
can only unbox a variable that has previously been boxed.
Casting
There are many conversions that cannot be implicitly made between types. If we attempt such
conversions, the compiler will give an error message. For example the following conversions
cannot be made implicitly:
1) int to short
2) float to int
However, we can explicitly carry out such conversions using the cast operator. This
process is known as casting.
Example:
long x = 1234L;
int y = ( int ) x;
double x =89.77;
double y =667.09;
int x = (int) (x+0.5); // x = 90
int y = (int) (y+0.5); // y = 667
Constants
Constants are unchanging types, associated with classes that are accessible at compile
time. Because of this latter fact, constants can only be value types rather than reference
types.Constant declarations take the 'const' keyword (not 'static', even though they are associated
with classes), and the five modifiers 'public', 'protected', 'internal', 'private' and 'new'.
The following is a simple constant declaration, although multiple constants can be simultaneously
declared.
public const int area = 4;
while loops
A 'while' loop executes a statement, or a block of statements wrapped in curly braces, repeatedly
until the condition specified by the boolean expression returns false. For instance, the following
code
int a = 0;
While (a < 3)
System.Console.WriteLine(a);
a++;
do-while loops
A 'do-while' loop is just like a 'while' loop except that the condition is evaluated after the block of
code specified in the 'do' clause has been run. So even where the condition is initially false, the
block runs once. For instance, the following code outputs '4':
int a = 4;
Do
System.Console.WriteLine(a);
a++;
for loops
The 'for' clause contains three parts. Statement1 is executed before the loop is entered. The loop
which is then executed corresponds to the following 'while' loop:
statement1
while (expression) {statement[s]3; statement2}
'For' loops tend to be used when one needs to maintain an iterator value. Usually, as in the
following example, the first statement initialises the iterator, the condition evaluates it against an
end value, and the second statement changes the iterator value.
1. for (int a =0; a<5; a++)
2. {
3. System.Console.WriteLine(a);
4. }
foreach loops
The 'foreach' loop is used to iterate through the values contained by any object which implements
the IEnumerable interface. When a 'foreach' loop runs, the given variable1 is set in turn to each
value exposed by the object named by variable2. As we have seen previously, such loops can be
used to access array values. So, we could loop through the values of an array in the following
way:
1. int[] a = new int[]{1,2,3};
2. foreach (int b in a)
3. System.Console.WriteLine(b);
The main drawback of 'foreach' loops is that each value extracted (held in the given example by
the variable 'b') is read-only.
Selection Statements
if - else
'If-else' statements are used to run blocks of code conditionally upon a boolean expression
evaluating to true. The 'else' clause, present in the following example, is optional.
1. if (a == 5)
2. System.Console.WriteLine("A is 5");
3. Else
If statements can also be emulated by using the conditional operator. The conditional operator
returns one of two values, depending upon the value of a boolean expression. To take a simple
example, the line of code
int i = (myBoolean) ? 1 : 0 ;
sets i to 1 if myBoolean is true, and sets i to 0 if myBoolean is false. The 'if' statement in the
previous code example could therefore be written like this:
1. System.Console.WriteLine( a==5 ? "A is 5" : "A is not 5");
switch - default
'Switch' statements provide a clean way of writing multiple if - else statements. In the following
example, the variable whose value is in question is 'a'. If a equals 1, then the output is 'a>0'; if a
equals 2, then the output is 'a>1 and a>0'. Otherwise, it is reported that the variable is not set.
1. switch(a)
2. {
3. Case 2:
5. goto case 1;
6. Case 1:
7. Console.WriteLine("a>0");
8. break;
9. default:
11. break;
12. }
Each case (where this is taken to include the 'default' case) will either have code specifying a
conditional action, or no such code. Where a case does have such code, the code must (unless the
case is the last one in the switch statement) end with one of the following statements:
break;
goto case k; (where k is one of the cases specified)
goto default;
From the above it can be seen that C# 'switch' statements lack the default 'fall through' behaviour
found in C++ and Java. However, program control does fall through wherever a case fails to
specify any action. The following example illustrates this point; the response "a>0" is given when
a is either 1 or 2.
1. switch(a)
2. {
3. Case 1:
4. Case 2:
5. Console.WriteLine("a>0");
6. break;
7. default:
9. break;
10. }
Jump Statements
Break
The 'break' statement breaks out of the 'while' and 'for' loops and the 'switch' statements. The
following code gives an example - albeit a very inefficient one - of how it could be used. The
output of the loop is from 0 to 4.
int a=0;
while(true)
{
System.Console.writeline(a);
a++;
if(a==5)
break;
}
continue
The 'continue' statement can be placed in any loop structure. When it executes, it moves the
program counter immediately to the next iteration of the loop. The following code example uses
the 'continue' statement to count the number of values between 1 and 100 inclusive that are not
multiples of seven. At the end of the loop the variable y holds the required value.
int y =0;
for(int x=0;x < 101 ; x++)
{
if ((x%7) = = 0)
continue;
y++;
}
goto
The 'goto' statement is used to make a jump to a particular labelled part of the program code. It is
also used in the 'switch' statement described below. We can use a 'goto' statement to construct a
loop, as in the following example (but again, this usage is not recommended):
int a = 0;
start:
system.console.writeline(a);
a++;
if(a<5)
goto start;
Declaring Methods
Modifiers:
Public – The method can be accessed from any where, including outside the class
Protected – The method can be accessed from within the class to which it belongs, or a type
derived from that class.
Private – The method can only be accessed from inside the class to which it belongs.
Static – The method does not operate on a specific instance of the class.
Example 1:
using system;
class methodex
{
int cube(int x)
{
return(x * x * x);
}
}
class methodtest
{
public static void Main( )
{
methodex m = new methodex;
int y = m.cube(5);
system.console.writeline(y);
}
}
Example 2:
using system;
class statictest
{
public static void Main( )
{
double y = square(2.5F);
system.console.writeline(y);
}
Nesting of methods:
using system;
class nesting
{
void largest(int n, int m)
{
int large= max(m,n);
system.console.writeline(large);
}
class nestingtest
{
public static void Main( )
{
nesting N = new nesting();
N.largest(100,200);
}
}
‘Read – Only’ modifier is used to set the value for the constant member at runtime and also to
have different value for different object of the class. Value can be set to the member using a
constructor method, but cannot be modified later.
‘Read – Only’ member may be declared as either static or instance fields. If instance they have
different values with different objects.
class Number
{
public readonly int m;
public static readonly int n;
public Number( int x)
{
m = x;
}
static Numbers( )
{
n = 100;
}
}
Pass By Value
By default method parameters are passed by value. That is, a parameter declared with no modifier
is passed by value and is called a value parameter. When a method is invoked, the values of
actual parameters are assigned to the corresponding formal parameters. The value parameters can
be changed within the methods.
using System;
class Test
{
static void TestMtd ( int M)
{
M + = 10;
}
Pass By Reference
We can use the ref keyword to force the value parameters to be passed by reference. A parameter
declared with ref modifier is a reference parameter.
void Modify ( ref int x )
Here, x is declared as a reference parameter.
Unlike a value parameter, a reference parameter does not create a new storage location. Instead, it
represents the same storage location as the actual parameter used in the method invocation. When
a formal parameter is declared as ref, the corresponding argument in the method invocation must
also be declared as ref.
In c# we can define methods that can handle variable number of arguments using what
are known as parameter arrays. Parameter arrays are declared using the keyword params.
using system;
class paramstest
{
static void parray(params int [] arr)
{
system.console.write(“Array elements are : “);
foreach (int i in arr)
system.console.write(“ “ + arr[i]);
system.console.writeline();
}
Method Overloading
C# allows us to create more than one method with the same name, but with the different
parameter lists and different definitions. This is called method overloading. Method overloading
is used when methods are required to perform similar tasks but using different input parameter.
using system;
class overloading
{
public static void main()
{
system.console.writeline(volume(10));
system.console.writeline(volume(2.5F,8));
system.console.writeline(volume(100L,75,15));
}
Arrays
Single-Dimensional Arrays
The type of each array declared is given firstly by the type of basic elements it can hold, and
secondly by the number of dimensions it has. Single-dimensional arrays have a single dimension
(ie, are of rank 1). They are declared using square brackets, eg:
int[] i = new int[100];
This line of code declares variable i to be an integer array of size 100. It contains space for 100
integer elements, ranging from i[0] to i[99].
To populate an array one can simply specify values for each element, as in the following code:
int [] i = new int[2];
i[0]=1;
i[1]=2;
One can also run together the array declaration with the assignment of values to elements using
int[] i = new int[] {1,2};
Rectangular Arrays
C# supports two types of multidimensional arrays: rectangular and jagged. A rectangular array is
a single array with more than one dimension, with the dimensions' sizes fixed in the array's
declaration. The following code creates a 2 by 3 multi-dimensional array:
int[,] squareArray = new int[2,3];
As with single-dimensional arrays, rectangular arrays can be filled at the time they are declared.
For instance, the code
int [,] squareArray = {{1, 2, 3}, {4, 5, 6}};
creates a 2 by 3 array with the given values. It is, of course, important that the given values do fill
out exactly a rectangular array.
In C#, every array we create is automatically derived from the System.Array class. Some
commonly used methods of System.Array class are
CopyTo ( ) – Copies elements from the source array into the destination array.
System.Collections namespace defines a class know as Arraylist that can store a dynamically
sized array of objects. An arraylist is very similar to an array, except that it has the ability to grow
dynamically.
countries.Add(“India”);
countries.Add(“Australia”);
Example:
using Sytsem;
using System.Collections;
class ArrayTest
country.Add(“India”);
country.Add(“Iran”);
country.Add(“Australia”);
country.Add(“China”);
country.Sort( );
int i;
Console.WriteLine(country[i]);
Console.WriteLine( );
country.RemoveAt(2);
Console.WriteLine(country[i]);
Strings
The most common way to create a string is to assign a quoted string of characters known as string
literal to a string object. For example,
string Strtest;
Strtest = “test”;
Copying Strings:
Two ways:
1)Using the overloaded = operator
2)Using the static Copy method
Example:
string s2 = s1;
string s2 = string.Copy(s1);
Concatenating Strings
Two Ways:
1)Using the overloaded + operator
2)Using the static Concat method
Example:
string s3 = s1 + s2
string s3 = string.Concat(s1,s2)
Inserting String:
using System;
class strtest
{
public static void Main()
{
string s1="Hi";
string s2 = s1.Insert(1,"a");
String s3 = s2.Insert(3,"Hello");
System.console.writeLine(s3);
}
}
Compare Method:
There are two versions of overloaded static Compare method. The first one takes two strings as
parameters and compare them.
Example:
int n = string.Compare(s1,s2);
This performs a case-sensitive comparison and returns different integer values for different
conditions:
1) Zero integer, if s1 equal to s2
2) A positive integer (1), if s1 is greater than s2
3) A negative integer (-1), if s1 is less than s2
We can use such comparison statements in if statements like:
If ( string.Compare(s1,s2) = = 0 )
Console.WriteLine(“ They are Equal”);
The second version of Compare takes an additional bool type parameter to decide whether case
should be ignored or not. If the bool parameter is true, case is ignored.
int n = string.Compare(s1,s2,true);
Equals Methods:
There are two versions of Equals method. They are implemented as follows:
bool b1 = s2.Equals(s1);
bool b2 = string.Equals(s2,s1);
These methods return a Boolean value true if s1 and s2 are equal, otherwise false.
The = = operator:
A simple and natural way of testing the equality of strings is by using the overloaded = =
operator.
bool b1 = ( s1 = = s2);
we very often use such statements in decision statements, like
if ( s1 = = s2)
Console.WriteLine(“They are Equal”);
Finding Substrings
It is possible to extract substrings from a given string using the overloaded Substring method
available in string class. There are two version of Substring:
1) s.Substring(n)
2) s.Substring(n1,n2)
The first one extracts a substring starting from the nth position to the last character of the
string contained in s. The second one extracts a substring from s beginning at n1 position and
ending at n2 position.
Example:
string s1 = “New York”
string s2 = s1.Substring(5);
string s3 = s1.Substring(0,3);
string s4 = s1.Substring(5,8);
Arrays Of Strings:
Creation of string array:
using system;
class strtest
{
public static void Main()
{
string [ ] countries = { “India” , “Germany” , “America” , “France”
}
int n = countries.Length;
Array.sort(countries);
For(int i = 0 ; I < n; i++)
{
system.console.WriteLine(countries[i]);
}
system.console.WriteLine();
Array.Reverse(countries);
For(int i = 0; i < n; i ++)
{
system.console.WriteLine(countries[i]);
}}}
This Reference
C# supports the keyword this which is a reference to the object that called the method.
The this reference is available within all the member methods and always refers to the current
instance. It is normally used to distinguish between local and instance variables that have the
same name.
Example:
class Test
{
int x, y;
public static void SetXY(int x, int y)
{
this.x = x;
this.y = y;
}
………….
………….
}
in the assignment statements, this.x and this.y refer to the class members named x and y whereas
simple x and y refers to the parameters of the SetXY( ) method.
Constructors
Constructors enable an object to initialize itself when it is created. Constructors have the
same name as the class itself. They do not specify a return type, not even void. This is because
they do not return any value.
using system;
class Rectangle
length = x ;
width = y ;
class RectangleArea
Overloaded Constructor
Class Room
length = x;
width = y;
length = width = x;
Here, we are overloading the constructor method Room( ). An object representing a rectangular
room will be created as
On the other hand, if the room is square then we may create the corresponding object as
The Destructor
using System;
class SampleClass
{
// Constructor
public SampleClass()
{
Console.WriteLine("SampleClass - Constructor");
}
~SampleClass ()
{
Console.WriteLine("Destructor of SampleClass");
}
}
Console.WriteLine();
}
}
SampleClass - Constructor
Destructor of SampleClass
Like a (default) constructor, a destructor is automatically created for your class but you can also
create it if you want. A class can have only one constructor. If you don't create it, the compiler
would create it for your class. If you create it, the compiler would not create another. A destructor
cannot have an access level. A destructor is called when the memory that a class was used is no
longer needed. This is done automatically by the compiler. For this reason, you will hardly need
to create a constructor, since its job is automatically taken care of behind the scenes by the
compiler.
Inheritance
C# class can be reused in several ways. Reusability is achieved by designing new classes,
reusing all or some of the properties of existing ones. The mechanism of designing or
constructing one class from another is called inheritance. Inheritance can be classified as two:
1) Classical Inheritance
2) Containment Inheritance
Classical Inheritance:
Inheritance represents a kind of relationship between two classes. Let us consider two
classes A and B. we can create a class hierarchy such that B is derived from A.
Class A
Class B
Class A, the initial class that is used as the basis for the derived class is referred to as the
base class, parent class or super class. Class B, the derived class, is referred to as derived class,
child class or sub class.
A derived class is a completely new class that incorporates all the data and methods of its
base class. It can also have its own data and method members that are unique to itself. That is, it
can enhance the content and behavior of the base class.
A A
B
B C D
A A B
C
C# does not directly implement multiple inheritances. However, this concept is
implemented using a secondary inheritance path in the form of interfaces.
Containment Inheritance:
Example:
class A
{
……
}
class B
{
……
A a ; // a is contained in b
}
Bb;
In such cases, we say that the object a is contained in object b. This relationship between
a and b is referred to as ‘ has – a ‘ relationship. The outer class B which contains the inner class A
is termed as the parent class and the contained class A is termed as a ‘child‘class.
Simple inheritance:
using system;
class Item
{
public void Company( )
{
system.console.WriteLine(“Item Code = XXX”);
}
using system;
class Room
{
public int Length;
public int Breath;
public Room (int x ,int y) //base class constructor
{
Length = x;
Breath = y;
}
class InTest
{
public static void Main ( )
{
BedRoom room1 = new BedRoom(14,12,10);
int area1 = room1.Area(); // superclass method
int volume1 = room1.volume(); //subclass method
system.console.writeLine ( “ Area1 = “ + area1);
system.console.writeLine(“Volume1 = “ + volume1);
}
}
Defining an Interface:
An interface contains one or more methods but none of them are implemented in the
interface itself. It is the responsibility of the class that implements the interface to define the
implementation code for these members.
{
Member declaration;
}
Example:
interface Show
{
void Display ( );
}
Extending an interface:
Like classes, interfaces can also be extended. That is, an interface can be sub interfaced
from other interfaces. The new sub interface will inherit all the members of the super interface in
the manner similar to sub classes.
Example:
We can put all the methods of particular behavior category in one interface and the
members of another category in the other.
interface Addition
{
int Add ( int x, int y) ;
}
The interface Compute will have both the methods and any class implementing the
interface Compute should implement both of them; otherwise, it is an error
We can also combine several interfaces together into a single interface. Following
declarations are valid:
iterface I1
{
----
}
interface I2
{
-----
}
Implementing interfaces:
using system;
interface Addition
{
int Add ( ) ;
}
interface Multiplication
{
int Mul ( ) ;
}
class interTest
{
public static void Main ( )
{
Computation com = new Computation ( 10, 20);
using system;
interface Display
{
void print ( );
}
class test
{
public static void Main( )
{
D d = new D ( );
d.print ( );
The use of modifier new in the derived class “hides” the print method implemented in the base
class.
Abstract Classes
In a number of hierarchical applications, we would have one base class and a number of
different derived classes. The top-most base class simply acts as a base for others and is not
useful on its own. In such situations, we might not want any one to create its objects. We can do
this by making the base class abstract.
The abstract is a modifier and when used to declare a class indicates that the class cannot
be instantiated. Only its derived (that are not marked abstract) can be instantiated. Some
characteristics of an abstract class are:
………………
}
………..
}
………….
………….
Base b; //Error
Derived d; //ok
Abstract Methods
Similar to abstract classes, we can also create abstract methods. Where as instance
method declaration includes the modifier abstract, the method is said to be an abstract method
An abstract method is implicitly a virtual method and does not provide any implementation.
Therefore, an abstract method does not have method body.
Example:
public abstract void Draw(int x ,int y);
It can be declared only in abstract classes, it cannot take either static or virtual Modifier.
Its implementation must be provided in non-abstract derived classes by overriding the method.
Sometimes, we may like to prevent a class being further subclassed for security reasons.
A class that cannot be subclassed is called a sealed class. This is achieved in C# using the
modifier sealed as follows:
………..
…………..
Any attempt to inherit these classes will cause an error and the compiler will not allow it.
Declaring as class sealed prevents any unwanted extensions to the class. A sealed class cannot be
an abstract class.
Sealed Methods:
When an instance method declaration includes the sealed modifier, the method is said to
be a sealed. It means a derived class cannot override this method.
A sealed modifier is used to override an inherited virtual method with the same signature.
This means, the sealed modifier is always used in combination with the override modifier.
Example:
class A
{
class B : A
{
public sealed override void Fun ( )
{
……….
}
}
The sealed method Fun ( ) overrides the virtual method Fun ( ) defined in Class A. Any
derived class of B cannot further override the method Fun ( ).
Overriding Methods
We have seen that a method defined in a super class is inherited by its subclass and is
used by the objects created by the sub class. Method inheritance enables us to define and use
methods repeatedly in sub classes.
However, there may be some occasions when we want an object to respond to the same
method but behave differently when that method is called. That means, we should override the
method defined in the super class. This I possible by defining a method in the sub class that has
the same name, same arguments and same return type as a method in the super class. Then, when
that method is called, the method defined in the subclass is invoked and executed instead of the
one in the super class, provided that:
Example:
using system;
class Super
{
protected int x;
public Super ( int x )
{
this.x=x;
}
public virtual void Display ( ) // method defined with virtual
{
system.console.writeLine(“Super x = “ + x );
}
}
class Test
{
public static void Main ( )
{
Sub s1 = new Sub (100,200);
s1.Display ( );
}
}
Structures
Structures are similar to classes in c#. Although classes will be used to implement most
objects, it is desirable to use structs where simple composite data types are required.
Defining a Struct:
Example:
struct Student
{
public string Name;
public int RollNo;
public double TotalMarks;
}
The keyword struct declares Student as a new data type that hold three variables of
different data types. These variables are known as members or fields or elements. The identifier
Student can now be used to create variables of type Student.
Example:
Student s1;
s1 is a variable of type Student and has three member variables as defined by the template.
Member variables can be accessed using the simple dot notation as follows:
s1.Name = “John” ;
s1.RollNo = 12 ;
s1.TotalMarks = 575 ;
We may also use the member variables in expressions on the right hand side.
Example:
FinalMarks = s1.TotalMarks + 10 ;
using System;
struct Item
{
public string name;
public int code;
public double price;
}
class StructTest
{
}
}
We have seen that values may be assigned to the data members using struct objects and the dot
operator. We can also assign values to the data members using what are known as constructors.
using system;
struct Rect
{
int a,b;
public Rect ( int x, int y)
{
a=x;
b=y;
}
class TestRect
{
public static void Main ( )
{
Rect rr = new Rect(10,20)
rr.Display();
}
}
Enumerations
An enumeration is a user defined integer type which provides a way for attaching names to
numbers, there by increasing the comprehensibility of the code. The enum keyword automatically
enumerates a list of words by assigning those values 0, 1, 2 and so on.
Enumerator Initialization:
enum color
{
Red = 2,
Blue = 5,
Green = 6,
Yellow = 9
}
enum color
{
Red = 1,
Blue = Red + 1,
If the declaration of an enum member has no intilizer, then its value is set implicitly as follows:
• If it is the first member, its value is zero.
• Otherwise, its value is obtained by adding one to the value of the previous member.
enum Alphabets
{
A,
B = 3,
C,
D = 12,
E
}
Example:
using System;
class Area
{
public enum Shape
{
circle,
square
}
public void Areashape ( int x, Shape shape)
{
double area;
switch( shape)
{
case Shape.circle:
area = Math.PI * x * x;
Console.WriteLine(“Circle Area : “ + area );
break;
case Shape.square:
area = x * x;
Console.WriteLine(“Square Area : “ + area );
break;
default:
Console.WriteLine(“Invalid Input”);
}
}
class Test
{
public static void Main( )
{
Area ObjArea = new Area( );
Polymorphism
Polymorphism means ‘one name, many forms’. Essentially, polymorphism is the capability of
one objectto behave in multiple ways. Polymorphism can be achieved in two ways.
Polymorphism
Operation Inclusion
Polymorphism Polymorphism
Using
Using Virtual
Overloaded Methods
Methods
Operation Polymorphism
Example:
using System;
class Dog
{
}
class Cat
{
}
class Operation
{
static void Call(Dog d)
{
Console.WiteLine (“Dog is called”);
}
static void Call(Cat c)
{
Console.WriteLine(“Cat is called”);
}
public static void Main()
{
Dog dog=new Dog();
Cat cat= new Cat();
Call(dog);
Call(cat);
}
}
C# permits upcasting of an object of a derived class to an object of its base class. We cannot
downcast implicitly an object of a base class to an object of its derived classes.
Examples:
class Base { }
class Derived : Base { }
………………
………………
Base b = new Cerived ( ) ; // ok , upcasting
…………..
…………..
Derived d = new Base ( ) ; // Error, downcasting
…………….
…………….
Inclusion Polymorphism:
Inclusion polymorphism is achieved through the use of virtual functions. Inclusion polymorphism
allows you to implement methods of a derived class during run time.
The decision on exactly which method to call is delayed until runtime and, therefore, it is also
known as runtime polymorphism.
Example:
using System;
class DrawObj
{
public virtual void Draw( )
{
Console.WriteLine( “Base Draw”);
}
}
class Line : DrawObj
{
public override void Draw( )
{
Console.WriteLine(“Line Draw”);
}
}
class Circle : DrawObj
{
public override void Draw( )
{
Console.WriteLine(“ Circle Draw”):
}
}
class Test
{
public static void Mian( )
{
DrawObj objD = new DrawObj( );
objD = new Line( );
objD.Draw( );
objD = new Circle( );
objD.Draw( );
}
}
Properties
Properties are members that provide a flexible mechanism to read, write, or compute the values of
private fields. Properties can be used as though they are public data members, but they are
actually special methods called accessors. This enables data to be accessed easily while still
providing the safety and flexibility of methods.
Example:
using System;
class Number
get
return number;
set
number = value;
class Test
Console.WriteLine ( “ Number = “ + m );
The class new declares a property called ANumber of type int and defines a get accessor method (
also known as getter ) and a set accessor method ( also known as setter). The getter method used
the keyword return to return the field’s value to the caller. The settermethod sues the keyword
value to receive the value being passed in from the user. The type of value is determined by the
type of property.
Delegates
Delegate means method acting for another method. A Delegate in C# is a class type object and is
used to invoke a method that has been encapsulated into it at the time of its creation. Creating and
using delegates involve four steps.
• Delegate declaration
• Delegate Method definition
• Delegate instantiation
• Delegate invocation
A delegate declaration defines a class using the class System.Delagate as a base class. Delegate
methods are any functions (defined in a class) whose signature matches the delegate signature
exactly. The delegate instance holds the reference to delegate methods. The instance is used to
invoke the methods indirectly.
A delegate can be used to hold reference to a method of any class. The only requirement is that its
Signature must match the Signature of the method.
Delegate declaration
Delegate Methods
delegate void Delegate1();
public void F1() //instance method
{
Console.WriteLine ();
}
Static public void F2() // static method
{
Console.WriteLine(“F2”);
}
Similarly,
Delegate double Mathop (double x, double y)
Delegate Instantiation
//delegate declaration
delegate int Productdelegate (int x, int y);
class delegateSample
{
Static float product(float a, float b) //Siganture does not match
{
return(a*b);
}
Stat int product (int a, int b) // Signature matches
{
return(a*b);
}
//delegate instantiation
product delegate p =new productdelegate(product);
Delegate Invocation
int m= p(10,20);
delegate –object(parameter list)
Using Delegate
Using system;
Delegate int DeleMtd (int a, int b);
Class DM
{
public int AddMe(int a, int b)
{
return(a+b);
}
public int SubMe(int a, int b)
{
return(a-b);
}
}
class Test
{
Public Static Void Main()
{
DM objDM=new DM()
DeleMtd[] Deleobj = {new DeleMtd(objDM.Addme), new DeleMtd(objDM.SubMe)};
Int t1=Deleobj[0](6,5);
Int t2=Deleobj[1](6,5);
System.Console.WriteLine(“The result of t1: “+t1);
System.Console.WrteLine(“The result of t2:”+t2);
}
}
Exception Handling
An exception is a condition that is caused by a run time error in the program. The purpose of the
exception handling mechanism is to provide a means to detect and report on ‘exceptional
circumstances’. So that appropriate action can be taken. The mechanism suggests incorporation
of a separate error handling code that performs the following tasks:
• Find the problem (Hit the exception)
• Inform that an error has occurred (Throw the exception)
• Receive the error information (Catch the exception)
• Take corrective actions (Handle the exception)
To catch a particular type of exception in a piece of code, you have to first wrap it in a 'try' block
and then specify a 'catch' block matching that type of exception. When an exception occurs in
code within the 'try' block, the code execution moves to the end of the try box and looks for an
appropriate exception handler. For instance, the following piece of code demonstrates catching an
exception specifically generated by division by zero:
try
int zero = 0;
catch (System.DivideByZeroException e)
It is possible to have more than one catch statement in the catch block.
Example:
using System;
class Test
{
public static void Main( )
{
int [ ] a = { 5 , 10 };
int b = 5;
try
{
int x = a[2] / b – a[1];
}
catch ( Arithmetic Exception e)
{
Console.WriteLine( “Division by Zero” );
}
catch(IndexOutOfRangeException e)
{
Console.WriteLine(“Array Index Error”);
}
catch(ArrayTypeMisMatchException e)
{
Console.WriteLine(“Wrong Data Type”);
}
int y = a[1] / a[0] ;
Console.WriteLine(“y = “ + y);
}
}
'finally'block
You can optionally use a 'finally' block along with the try-catch. The 'finally' block is
guaranteed to be executed even if there is an exception. If an exception is raised, the code in the
finally block gets executed after the code in the catch block.
Example:
using System;
class Test
{
Formatted Output
We can produce formatted output using the overloaded WriteLine( ) method. This method takes
a string containing a format and a list of variables whose values have to be printed out. The
general form of formatted WriteLine( ) method is:
Console.WriteLine( format-string, v1, v2 ….. );
Format string contains both static text and markers which indicate
• Where the values to be printed
• How the values are to be formatted
In this simplest form the marker is an index number in curly brackets, that indicates which
variable of the argument list is to be substituted. Examples,
Console.WriteLine(“Total is {0}”, total);
Console.WriteLine(“ Sum of {0} and {1} is {2} “, a,b,c);
In this examples, {0} represents the first argument in the list, {1} represents the second, and so
on.
Example:
using System;
class test
{
public static void Main( )
{
string s = “Items”;
int a = 100;
float x = 67.66F;
Console.WriteLine(“{0}\nIntValue : {1}\n FloatValue : {2}”,s,a,x);
}
VB.NET
Visual Basic .NET (VB.NET) is an object-oriented computer language that can be viewed as an
spiritual evolution of Microsoft's Visual Basic (VB) implemented on the Microsoft .NET
framework. Its introduction has been controversial, as significant changes were made that broke
backward compatibility with VB and caused a rift within the developer community that may or
may not be resolved with the introduction of Visual Studio 2005.
Visual Basic .NET, the next generation of Visual Basic, is designed to be the easiest and
most productive tool for creating .NET applications, including Windows applications, Web
Services, and Web applications.
While providing the traditional ease-of-use of Visual Basic development, Visual Basic .NET
also allows optional use of new language features. Inheritance, method overloading,
structured exception handling, and free threading all make Visual Basic a powerful object-
oriented programming language. Visual Basic .NET fully integrates with the .NET
Framework and the Common Language Runtime, which together provide language
interoperability, simplified deployment, enhanced security, and improved versioning
support.
VB:
1. Object-based language
2. Does not support inheritance
3. ADO does not give support for disconnected data architecture
4. No interoperability function
5. No support for threading
VB.Net
Windows Forms
In Visual Basic its these Forms with which we work. They are the base on which we build,
develop all our user interface and they come with a rich set of classes. Forms allow us to work
visually with controls and other items from the toolbox. In VB .NET forms are based on the
System.Windows.Forms namespace and the form class is System.Windows.Forms.Form. The
form class is based on the Control class which allows it to share many properties and methods
with other controls.
When we open a new project in Visual Basic the dialogue box that appears first is the one which
looks like the image below. Since we are working with Windows Applications (Forms) you need
to select WindowsApplication and click OK.
Once you click OK a new Form opens with the title, Form1, towards the top-left side of the form
and maximize, minimize and close buttons towards the top right of the form. The whole form is
surrounded with a border. The main area of the form in which we work is called the Client Area.
It's in this client area we design the user interface leaving all the code to the code behind file.
Forms also support events which let's the form know that something happened with the form, for
example, when we double-click on the form, the Form load event occurs. VB .NET also supports
forms to be inherited.
Typically the Form looks like this in Code which is handled by the Framework.
Public Class Form1
Inherits System.Windows.Forms.Form
End Sub
End Sub
#End Region
End Sub
End Class
Controls
A control is an object that can be drawn on to the Form to enable or enhance user interaction with
the application. Examples of these controls, TextBoxes, Buttons, Labels, Radio Buttons, etc. All
these Windows Controls are based on the Control class, the base class for all controls. Visual
Basic allows us to work with controls in two ways: at design time and at runtime. Working with
controls at design time means, controls are visible to us and we can work with them by dragging
and dropping them from the Toolbox and setting their properties in the properties window.
Working at runtime means, controls are not visible while designing, are created and assigned
properties in code and are visible only when the application is executed. There are many new
controls added in Visual Basic.Net and we will be working with some of the most popular
controls in this section.
Notable properties of most of these Windows Controls which are based on the Control class itself
are summarized in the table below. You can always find the properties of the control with which
you are working by pressing F4 on the keyboard or by selecting View->Properties Window from
the main menu.
The Control class is in the System.Windows.Forms namespace. It is a base class for the Windows
Controls.
The properties of the Control object are summarized below. Properties are alphabetical as seen in
the properties window.
Indicates if the form can accept data that the user drags
AllowDrop
and drops into it
Anchor Gets/Sets which edges of the control are anchored
BackColor Gets/Sets the background color for the control
BackgroundImage Gets/Sets the back ground image in the control
Gets the distance bewteen the bottom of the control and
Bottom
the top of its container client area
Bounds Gets/Sets the controls bounding rectangle
CanFocus Returns a value specifying if the control can recieve focus
CanSelect Returns a value specifying if the control can be selected
Gets/Sets a value specifying if the control has captured the
Capture
mouse
Gets/Sets a value specfying if the control causes
CausesValidation
validation for all controls that require validation
Button Control
One of the most popular control in Visual Basic is the Button Control (previously Command
Control). They are the controls which we click and release to perform some action. Buttons are
used mostly for handling events in code, say, for sending data entered in the form to the database
and so on. The default event of the Button is the Click event and the Button class is based on the
ButtonBase class which is based on the Control class.
Button Event
The default event of the Button is the Click event. When a Button is clicked it responds with the
Click Event. The Click event of Button looks like this in code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
'You place the code here to perform action when Button is clicked
End Sub
Well, it's time to work with Buttons. Drag a Button from the toolbox onto the Form. The default
text on the Button is Button1. Click on Button1 and select it's properties by pressing F4 on the
keyboard or by selecting
View->Properties Window from the main menu. That displays the Properties for Button1.
Appearance
Appearance section of the properties window allows us to make changes to the appearance of the
Button. With the help of BackColor and Back Ground Image properties we can set a background
color and a background image to the button. We set the fontcolor and font style for the text that
appears on button with ForeColor and the Font property. We change the appearance style of the
button with the FlatStyle property. We can change the text that appears on button with the Text
property and with the TextAlign property we can set where on the button the text should appear
from a predefined set of options.
Behavior
Notable Behavior properties of the Button are the Enabled and Visible properties. The Enabled
property is set to True by default which makes the button enabled and setting it's property to False
makes the button Disabled. With the Visible property we can make the Button Visible or
Invisible. The default value is set to True and to make the button Invisible set it's property to
False.
Layout
Layout properties are about the look of the Button. Note the Dock property here. A control can be
docked to one edge of its parent container or can be docked to all edges and fill the parent
container. The default value is set to none. If you want to dock the control towards the left, right,
top, bottom and center you can do that by selecting from the button like image this property
displays. With the Location property you can change the location of the button. With the Size
property you can set the size of the button. Apart from the Dock property you can set it's size and
location by moving and stretching the Button on the form itself.
TextBox Control
Windows users should be familiar with textboxes. This control looks like a box and accepts input
from the user. The TextBox is based on the TextBoxBase class which is based on the Control
class. TextBoxes are used to accept input from the user or used to display text. By default we can
enter up to 2048 characters in a TextBox but if the Multiline property is set to True we can enter
up to 32KB of text. The image below displays a Textbox.
Some important properties in the Behavior section of the Properties Window for TextBoxes.
TextAlign: Allows to align the text from three possible options. The default value is left and you
can set the alignment of text to right or center.
Scrollbars: Allows to add a scrollbar to a Textbox. Very useful when the TextBox is multiline.
You have four options with this property. Options are are None, Horizontal, Vertical and Both.
Depending on the size of the TextBox anyone of those can be used.
TextBox Event
The default event of the TextBox is the TextChanged Event which looks like this in code:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal
e As _
System.EventArgs) Handles TextBox1.TextChanged
End Sub
Drag two TextBoxes (TextBox1, TextBox2) and a Button (Button1) from the toolbox.
We want to display some text, say, "Welcome to TextBoxes", in TextBox1 when the Button is
clicked. The code looks like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
TextBox1.Text = "Welcome to TextBoxes"
End Sub
Set the PasswordChar property of TextBox2 to *. Setting that will make the text entered in
TextBox2 to be displayed as *. We want to display what is entered in TextBox2 in TextBox1.
The code for that looks like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
TextBox1.Text = TextBox2.Text
End Sub
When you run the program and enter some text in TextBox2, text will be displayed as *. When
you click the Button, the text you entered in TextBox2 will be displayed as plain text in
TextBox1.
We can make sure that a TextBox can accept only characters or numbers which can restrict
accidental operations. For example, adding two numbers of the form 27+2J cannot return
anything. To avoid such kind of operations we use the KeyPress event of the TextBox.
Code that allows you to enter only double digits in a TextBox looks like this:
Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As_
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If(e.KeyChar < "10" Or e.KeyChar > "100") Then
MessageBox.Show("Enter Double Digits")
End If
End Sub
RichTextBox
RichTextBoxes are similar to TextBoxes but they provide some advanced features over the
standard TextBox. RichTextBox allows formatting the text, say adding colors, displaying
particular font types and so on. The RichTextBox, like the TextBox is based on the TextBoxBase
class which is based on the Control class. These RichTextBoxes came into existence because
many word processors these days allow us to save text in a rich text format. With RichTextBoxes
we can also create our own word processors. We have two options when accessing text in a
RichTextBox, text and rtf (rich text format). Text holds text in normal text and rtf holds text
in rich text format.
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
Drag a RichTextBox (RichTextBox1) and a Button (Button1) onto the form. Enter some text in
RichTextBox1, say, "We are working with RichTextBoxes". 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")
'using the Find method to find the text "are" and setting it's
'return property to SelectionStart which selects the text to format
Dim ifont As New Font(RichTextBox1.Font, FontStyle.Italic)
'creating a new font object to set the font style
RichTextBox1.SelectionFont = ifont
'assigning the value selected from the RichTextBox the font style
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.
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 _
The output when the Button is Clicked is the text "are" being displayed in Blue and the text
"working" in yellow as shown in the image below.
Drag two RichTextBoxes 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")
'using SaveFile method to save text in a rich text box to hard disk
End Sub
Label
Labels are those controls that are used to display text in other parts of the application. They are
based on the Control class.
Notable property of the label control is the text property which is used to set the text for the label.
Label Event
The default event of Label is the Click event which looks like this in code:
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs)_
Handles Label1.Click
End Sub
LinkLabel
LinkLabel is similar to a Label but they display a hyperlink. Even multiple hyperlinks can be
specified in the text of the control and each hyperlink can perform a different task within the
application. They are based on the Label class which is based on the Control class.
Notable properties of the LinkLabel control are the ActiveLinkColor, LinkColor and LinkVisited
which are used to set the link color.
LinkLabel Event
The default event of LinkLabel is the LinkClicked event which looks like this in code:
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)_
Handles LinkLabel1.LinkClicked
End Sub
Drag a LinkLabel (LinkLabel1) onto the form. When we click this LinkLabel it will take us
to "www.startvbdotnet.com". The code for that looks like this:
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object,
ByVal_
e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)_
Handles LinkLabel1.LinkClicked
System.Diagnostics.Process.Start("www.startvbdotnet.com")
'using the start method of system.diagnostics.process class
'process class gives access to local and remote processes
End Sub
CheckBox
CheckBoxes are those controls which gives us an option to select, say, Yes/No or True/False. A
checkbox is clicked to select and clicked again to deselect some option. When a checkbox is
selected a check (a tick mark) appears indicating a selection. The CheckBox control is based on
the TextBoxBase class which is based on the Control class. Below is the image of a Checkbox.
Notable Properties
Important properties of the CheckBox in the Appearance section of the properties window are:
Appearance: Default value is Normal. Set the value to Button if you want the CheckBox to be
displayed as a Button.
BackgroundImage: Used to set a background image for the checkbox.
CheckAlign: Used to set the alignment for the CheckBox from a predefined list.
Checked: Default value is False, set it to True if you want the CheckBox to be displayed as
checked.
CheckState: Default value is Unchecked. Set it to True if you want a check to appear. When set to
Indeterminate it displays a check in gray background.
FlatStyle: Default value is Standard. Select the value from a predefined list to set the style of the
checkbox.
Important property in the Behavior section of the properties window is the ThreeState property
which is set to False by default. Set it to True to specify if the Checkbox can allow three check
states than two.
CheckBox Event
The default event of the CheckBox is the CheckedChange event which looks like this in code:
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
End Sub
Lets work with an example. Drag a CheckBox (CheckBox1), TextBox (TextBox1) and a Button
(Button1) from the Toolbox.
RadioButton
RadioButtons are similar to CheckBoxes but RadioButtons are displayed as rounded instead of
boxed as with a checkbox. Like CheckBoxes, RadioButtons are used to select and deselect
options but they allow us to choose from mutually exclusive options. The RadioButton control is
based on the ButtonBase class which is based on the Control class. A major difference between
CheckBoxes and RadioButtons is, RadioButtons are mostly used together in a group. Below is
the image of a RadioButton.
Important properties of the RadioButton in the Appearance section of the properties window are:
Appearance: Default value is Normal. Set the value to Button if you want the RadioButton to be
displayed as a Button.
BackgroundImage: Used to set a background image for the RadioButton.
CheckAlign: Used to set the alignment for the RadioButton from a predefined list.
Checked: Default value is False, set it to True if you want the RadioButton to be displayed as
checked.
FlatStyle: Default value is Standard. Select the value from a predefined list to set the style of the
RadioButton.
RadioButton Event
The default event of the RadioButton is the CheckedChange event which looks like this in code:
Private Sub RadioButton1_CheckedChanged(ByVal sender As
System.Object,_
ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
End Sub
Drag a RadioButton (RadioButton1), TextBox (TextBox1) and a Button (Button1) from the
Toolbox.
ListBox
The ListBox control displays a list of items from which we can make a selection. We can select
one or more than one of the items from the list. The ListBox control is based on the ListControl
class which is based on the Control class. The image below displays a ListBox.
HorizontalScrollbar: Displays a horizontal scrollbar to the ListBox. Works when the ListBox has
MultipleColumns.
MultiColumn: The default value is set to False. Set it to True if you want the list box to display
multiple columns.
ScrollAlwaysVisible: Default value is set to False. Setting it to True will display both Vertical
and Horizontal scrollbar always.
SelectionMode: Default value is set to one. Select option None if you do not any item to be
selected. Select it to MultiSimple if you want multiple items to be selected. Setting it to
MultiExtended allows you to select multiple items with the help of Shift, Control and arrow keys
on the keyboard.
Sorted: Default value is set to False. Set it to True if you want the items displayed in the ListBox
to be sorted by alphabetical order.
Notable property in the Data section of the Properties window is the Items property. The Items
property allows us to add the items we want to be displayed in the list box. Doing so is simple,
click on the ellipses to open the String Collection Editor window and start entering what you
want to be displayed in the ListBox. After entering the items click OK and doing that adds all the
items to the ListBox.
ListBox Event
The default event of ListBox is the SelectedIndexChanged which looks like this in code:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As
System.Object, _
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
End Sub
Drag a TextBox and a ListBox control to the form and add some items to the ListBox with it's
items property.
Items in a ListBox are referred by index. When items are added to the ListBox they are assigned
an index. The first item in the ListBox always has an index of 0 the next 1 and so on.
When you run the code and select an item from the ListBox, it's index is displayed in the textbox.
Add a Button to the form and place the following code in it's click event.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles Button1.Click
TextBox1.Text = ListBox1.Items.Count
'counting the number of items in the ListBox with the Items.Count
End Sub
When you run the code and click the Button it will display the number of items available in the
ListBox.
When you run the code and click an item in the ListBox that item will be displayed in the
TextBox.
You can remove all items or one particular item from the list box.
ComboBox
The DropDownStyle property in the Appearance section of the properties window allows us to
set the look of the ComboBox. The default value is set to DropDown which means that the
ComboBox displays the Text set by it's Text property in the Textbox and displays it's items in the
DropDownListBox below. Setting it to simple makes the ComboBox to be displayed with a
TextBox and the list box which doesn't drop down. Setting it to DropDownList makes the
ComboBox to make selection only from the drop down list and restricts you from entering any
text in the textbox.
We can sort the ComboBox with it's Sorted property which is set to False by Default. We can add
items to the ComboBox with it's Items property.
ComboBox Event
The default event of ComboBox is SelectedIndexChanged which looks like this in code:
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As
System.Object,_
ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub
Drag a ComboBox and a TextBox control onto the form. To display the selection made in the
ComboBox in the Textbox the code looks like this:
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As
System.Object,_
ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
TextBox1.Text = ComboBox1.SelectedItem
'selecting the item from the ComboBox with selected item property
End Sub
You can remove all items or one particular item from the list box part of the ComboxBox. Code
to remove a particular item by it's Index number looks like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
ComboBox1.Items.RemoveAt(4)
'removing an item by specifying it's index
End Sub
TreeView
The tree view control is used to display a hierarchy of nodes (both parent, child). You can expand
and collpase these nodes by clicking them. This control is similar to Windows Explorer which
displays a tree view in it's left pane to list all the folders on the hard disk. Below is the image of a
Tree View control.
TreeView Event
Default event of the Tree View control is the AfterSelect event which looks like this in code:
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e
As_
System.Windows.Forms.TreeViewEventArgs) Handles
TreeView1.AfterSelect
End Sub
Drag a Tree View control on to a form and to add nodes to it select the nodes property in the
properties window, which displays the TreeNode editor as shown below.
To start adding nodes, you should click the Add Root button, which adds a top-level node. To add
child nodes to that node, you should select that node and use the Add Child button. To set text
for a node, select the node and set it's text in the textbox as shown in the image above.
Assuming you added some nodes to the tree view, drag two Labels (Label1, Label2) from the
toolbox on to the form. The following code displays the node you select on Label2 and the path to
that node on Label1. The code looks like this:
Public Class Form12 Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
#End Region
End Class
CheckedListBox
The notable property in the appearance section of the properties window is the
ThreeDCheckBoxes property which is set to False by default. Setting it to True makes the
CheckedListBox to be displayed in Flat or Normal style.
Notable property in the behavior section is the CheckOnClick property which is set to False by
default. When set to False it means that to check or uncheck an item in the CheckedListBox we
need to double-click the item. Setting it to True makes an item in the CheckedListBox to be
checked or unchecked with a single click.
Notable property in the Data section is the Items property with which we add items to the
CheckedListBox.
Private Sub CheckedListBox1_SelectedIndexChanged(ByVal sender As
System.Object,_
ByVal e As System.EventArgs) Handles
CheckedListBox1.SelectedIndexChanged
End Sub
Panel
Panels are those controls which contain other controls, for example, a set of radio buttons,
checkboxes, etc. Panels are similar to Groupboxes but the difference, Panels cannot display
captions where as GroupBoxes can and Panels can have scrollbars where as GroupBoxes can't. If
the Panel's Enabled property is set to False then the controls which the Panel contains are also
disabled. Panels are based on the ScrollableControl class.
Notable property of the Panel control in the appearance section is the BorderStyle property. The
default value of the BorderStyle property is set to None. You can select from the predefined list
to change a Panels BorderStyle.
Notable property in the layout section is the AutoScroll property. Default value is set to False. Set
it to True if you want a scrollbar with the Panel.
On a from drag a Panel (Panel1) from the toolbox. We want to place some controls, say,
checkboxes on this Panel. Drag three checkboxes from the toolbox and place them on the Panel.
When that is done all the checkboxes in the Panel are together as in a group but they can function
independently.
GroupBox Control
As said above, Groupboxes are used to Group controls. GroupBoxes display a frame around them
and also allows to display captions to them which is not possible with the Panel control. The
GroupBox class is based on the Control class.
PictureBox Control
PictureBoxes are used to display images on them. The images displayed can be anything varying
from Bitmap, JPEG, GIF, PNG or any other image format files. The PictureBox control is based
on the Control class.
Notable property of the PictureBox Control in the Appearance section of the properties window is
the Image property which allows to add the image to be displayed on the PictureBox.
Images can be added to the PictureBox with the Image property from the Properties window or
by following lines of code.
Private Sub Button1_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles Button1.Click
PictureBox1.Image = Image.FromFile("C:\sample.gif")
'loading the image into the picturebox using the FromFile method of the image
class
'assuming a GIF image named sample in C: drive
End Sub
ToolTip
ToolTips are those small windows which display some text when the mouse is over a control
giving a hint about what should be done with that control. ToolTip is not a control but a
component which means that when we drag a ToolTip from the toolbox onto a form it will be
displayed on the component tray. Tooltip is an Extender provider component which means that
when you place an instance of a ToolTipProvider on a form, every control on that form receives a
new property. This property can be viewed and set in the properties window where it appears as
Tooltip on n, where n is the name of the ToolTipProvider.
Notable property of the ToolTip is the Active property which is set to True by default and which
allows the tool tip to be displayed.
Setting a ToolTip
Assume that we have a TextBox on the form and we want to display some text when your mouse
is over the TextBox. Say the text that should appear is "Do not leave this blank". The code for
that looks like this:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
ToolTip1.SetToolTip(TextBox1, "Do not leave this blank")
End Sub
ErrorProvider Component
The ErrorProvider component provides an easy way to set validation errors. It allows us to set an
error message for any control on the form when the input is not valid. When an error message is
set, an icon indicating the error will appear next to the control and the error message is displayed
as Tool Tip when the mouse is over the control.
Notable property of ErrorProvider in the Appearance section is the Icon property which allows us
to set an icon that should be displayed. Notable property in Behavior section is the BlinkRate
property which allows to set the rate in milliseconds at which the icon blinks.
Displaying an Error
Let's work with an example. Assume we have a TextBox and a Button on a form. If the TextBox
on the form is left blank and if the Button is clicked, an icon will be displayed next to the
TextBox and the specified text will appear in the Tool Tip box when the mouse is over the
control. The code for that looks like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
ErrorProvider1.SetError(TextBox1, "Cannot leave textbox blank")
Else
ErrorProvider1.SetError(TextBox1, "")
End If
End Sub
Menus
Everyone should be familiar with Menus. Menus (File, Edit, Format etc in all windows
applications) are those that allow us to make a selection when we want to perform some action
with the application, for example, to format the text, open a new file, print and so on. In VB .NET
MainMenu is the container for the Menu structure of the form. Menus are made of MenuItem
objects that represent individual parts of a menu (like File->New, Open, Save, Save As etc). The
two main classes involved in menu handling are, MainMenu and MenuItem. The MainMenu class
let's us assign objects to a form's menu class and MenuItem is the class which supports the items
in a menu system. Menus like File, Edit, Format etc and the items in those Menus are supported
by this MenuItem class. It's this MenuItem's click event that makes these Menus work. For a
MenuItem to be displayed, we need to add it to a MainMenu object.
The default event of the MenuItem is the Click event which looks like this in code:
Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles MenuItem1.Click
End Sub
Checked: Default value is set to False. Changing it to True makes a checkmark appear towards
the left of the Menu.
DefaultItem: Default value is set to False. Changing it to True makes this menu item default
menu item.
RadioCheck: Changing it to True makes a menu item display a radio button instead of a
checkmark.
Shortcut: Enables to set a short cut key from a list of available shortcuts for the menu item.
Creating Menus is simple. Drag a MainMenu component from the toolbar onto the form. When
you add a MaiuMenu component to the form it appears in the component tray below the form.
Windows form designer will add the MenuItem's for this by default, you need not add this. Once
when you finish adding a MainMenu component to the form you will notice a "TypeHere" box
towards the top-left corner of the form. To create a menu all you have to do is click on the
"TypeHere" text which opens up a small textbox allowing you to enter text for the menu. You can
view that in the image below. You can use the arrow keys on the keyboard to create a submenu or
add other items to that menu or click on the first menu item and use the left/right arrow keys on
the keyboard to create a new menu item. That's all it takes to add a menu to the form.
Let's work with an example to understand Menus. Drag a MainMenu and a TextBox onto the
form. In the "Type Here" part, type File and under file type "New" and "Exit". Our intention here
is to display "Welcome to Menus" in the TextBox when "New" is clicked and close the form
when "Exit" is clicked. The Menu which we will create should look like this File->New, Exit
(New and Exit below File). The code for that looks like this:
Public Class Form3 Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
End Class
Context Menus
Context menus are menus that appear when an item is right-clicked. In any windows application
when you right-click your mouse you get a menu which might display some shortcuts from the
Edit Menu, for example, cut, copy, paste, paste special and so on. All these menu items which are
available when you right-click are called Context Menus. In Visual Basic we create context
menus with the ContextMenu component. The ContextMenu component is edited exactly the
same way the MainMenu component is edited. The ContextMenu appears at the top of the form
and you can add menu items by typing them. To associate a ContextMenu with a particular form
or control we need to set the ContextMenu property of that form or control to the appropriate
menu.
#End Region
End Class
You can run the application, enter some text in richtextbox1, cut/copy it and paste it in
richtextbox2. The images below display sample output from the above said code.
Common Dialogs
Visual Basic .NET comes with built-in dialog boxes which allow us to create our own File Open,
File Save, Font, Color dialogs much like what we see in all other windows applications. To make
a dialog box visible at run time we use the dialog box's ShowDialog method. The Dialog Boxes
which come with Visual Basic .NET are: OpenFileDialog, SaveFileDialog, FontDialog,
ColorDialog, PrintDialog, PrintPreviewDialog and PageSetupDialog. We will be working with
OpenFile, SaveFile, Font and Color Dialog's in this section. The return values of all the above
said dialog boxes which will determine which selection a user makes are: Abort, Cancel, Ignore,
No, None, OK, Return, Retry and Yes.
OpenFileDialog
Open File Dialog's are supported by the OpenFileDialog class and they allow us to select a file to
be opened. Below is the image of an OpenFileDialog.
AddExtension: Gets/Sets if the dialog box adds extension to file names if the user doesn't supply
the extension.
CheckFileEixsts: Checks whether the specified file exists before returning from the dialog.
CheckPathExists: Checks whether the specified path exists before returning from the dialog.
DefaultExt: Allows you to set the default file extension.
FileName: Gets/Sets file name selected in the file dialog box.
FileNames: Gets the file names of all selected files.
Filter: Gets/Sets the current file name filter string, which sets the choices that appear in the "Files
of Type" box.
FilterIndex: Gets/Sets the index of the filter selected in the file dialog box.
InitialDirectory: This property allows to set the initial directory which should open when you use
the OpenFileDialog.
MultiSelect: This property when set to True allows to select multiple file extensions.
ReadOnlyChecked: Gets/Sets whether the read-only checkbox is checked.
RestoreDirectory: If True, this property restores the original directory before closing.
ShowHelp: Gets/Sets whether the help button should be displayed.
ShowReadOnly: Gets/Sets whether the dialog displays a read-only check box.
Title: This property allows to set a title for the file dialog box.
ValidateNames: This property is used to specify whether the dialog box accepts only valid file
names.
SaveFileDialog
Save File Dialog's are supported by the SaveFileDialog class and they allow us to save the file
in a specified location. Below is the image of a SaveFileDialog.
Properties of the Save File Dialog are the same as that of the Open File Dialog. Please refer
above. Notable property of Save File dialog is the OverwritePromopt property which displays a
warning if we choose to save to a name that already exists.
FontDialog
Font Dialog's are supported by the FontDialog Class and they allow us to select a font size,
face, style, etc. Below is the image of a FontDialog.
AllowSimulations: Gets/Sets whether the dialog box allows graphics device interface font
simulations.
AllowVectorFonts: Gets/Sets whether the dialog box allows vector fonts.
AllowVerticalFonts: Gets/Sets whether the dialog box displays both vertical and horizontal fonts
or only horizontal fonts.
Color: Gets/Sets selected font color.
FixedPitchOnly: Gets/Sets whether the dialog box allows only the selection of fixed-pitch fonts.
Font: Gets/Sets the selected font.
FontMustExist: Gets/Sets whether the dialog box specifies an error condition if the user attempts
to select a font or size that doesn't exist.
MaxSize: Gets/Sets the maximum point size the user can select.
MinSize: Gets/Sets the mainimum point size the user can select.
ShowApply: Gets/Sets whether the dialog box contains an apply button.
ShowColors: Gets/Sets whether the dialog box displays the color choice.
ShowEffects: Gets/Sets whether the dialog box contains controls that allow the user to specify to
specify strikethrough, underline and text color options.
ShowHelp: Gets/Sets whether the dialog box displays a help button.
ColorDialogs
Color Dialog's are supported by the ColorDialog Class and they allow us to select a color. The
image below displays a color dialog.
AllowFullOpen: Gets/Sets whether the user can use the dialog box to define custom colors.
AnyColor: Gets/Sets whether thedialog box displays all the available colors in the set of basic
colons.
Color: Gets/Sets the color selected by the user.
CustomColors: Gets/Sets the set of custom colors shown in the dialog box.
FullOpen: Gets/Sets whether the controls used to create custom colors are visible when the dialog
box is opened.
ShowHelp: Gets/Sets whether the dialog box displays a help button.
SolidColorOnly: Gets/Sets whether the dialog box will restrict users to selecting solid colors only
We will work with OpenFile, SaveFile, Font and Color Dialog's in this section. From the toolbox
drag a MainMenu component, RichTextBox control, Button Control, OpenFileDialog,
SaveFileDialog, FontDialog and ColorDialog onto the form. The sample code demonstrated
below allows you to select a file to be opened and displays it in the RichTextBox with
OpenFileDialog, allows you to save the text you enter in the RichTextBox to a location using the
SaveFileDialog, allows you to select a font and applies the selected font to text in the RTB
using FontDialog and allows you to select a color and applies the color to text in the RTB using
the ColorDialog. Select the MainMenu component and in the "Type Here" part of the MainMenu
type File and using the down arrow keys on the keyboard start typing Open, Save, SelectFont and
SelectColor under the File menu. It should look like this: File-> Open, Save, SelectFont,
SelectColor. We will assign OpenFileDialog to Open, SaveFileDialog to Save, FontDialog to
SelectFont and ColorDialog to SelectColor under File Menu. The form in design view should
look similar to the image below.
Before proceeding further you need to set properties for these dialogs in their properties window.
They are listed below.
For OpenFileDialog1, set the DefaultExt property to txt so that it opens text files, InitialDirectory
property to C:, RestoreDirectory propery to True and the Text property to Open File From.
For SaveFileDialog1, set the DefaultExt property to txt so that it saves files in text format,
InitialDirectory property to C: so that when you save a file, it first provides C: drive as the choice
of location, OverwritePrompt property to False, RestoreDirectory propery to True and the Text
property to Save File In.
Code
Imports System.IO
Public Class Form1 Inherits System.Windows.Forms.Form
#End Region
Catch es As Exception
MessageBox.Show(es.Message)
Finally
If Not (sw Is Nothing) Then
sw.Close()
End If
End Try
End Sub
End Class
Date TimePicker
Date TimePicker allows us to select date and time. Date TimePicker is based on the control class.
When we click on the drop-down arrow on this control it displays a month calendar from which
we can make selections. When we make a selection that selection appears in the textbox part of
the Date TimePicker. The image below displays the Date TimePicker.
The Format property in the Appearance section is used to select the format of the date and time
selected. Default value is long which displays the date in long format. Other values include short,
time and custom
Behavior Section
The CustomFormat property allows us to set the format for date and time depending on what we
like. To use the CustomFormat property we need to set the Format property to Custom.
The MaxDate Property allows us to set the maximum date we want the Date TimePicker to hold.
Default MaxDate value set by the software is 12/31/9998 .
The MinDate Property allows us to set the minimum date we want the Date TimePicker to hold.
Default MinDate value set by the software is 1/1/1753 .
MonthCalendar
The MonthCalendar control allows us to select date. The difference between a Date TimePicker
and MonthCalendar is, in MonthCalendar we select the date visually and in Date TimePicker
when we want to make a selection we click on the drop-down arrow and select the date from the
MonthCalendar which is displayed. The image below displays a MonthCalendar control.
FirstDayOfWeek: Default value is Default which means that the week starts with Sunday as the
first day and Saturday as last. You can set the first day of the week depending upon your choice
by selecting from the predefined list with this property.
ShowToday: Default value is set to True which displays the current date at the bottom of the
Calendar. Setting it to False will hide it.
ShowTodayCircle: Default value is set to True which displays a red circle on the current date.
Setting it to False will make the circle disappear.
ShowWeekNumber: Default is False. Setting it to True will display the week number of the
current week in the 52 week year. That will be displayed towards the left side of the control.
Splitter
The Splitter control is used to resize other controls. The main purpose of Splitter control is to
save space on the form. Once when we finish working with a particular control we can move it
away from it's position or resize them with Splitter control. The Splitter control is invisible when
we run the application but when the mouse is over it, the mouse cursor changes indicating that it's
a Splitter control and it can be resized. This control can be very useful when we are working with
controls both at design time and run time (which are not visible at design time). The Splitter
control is based on the Control class.
To work with a Splitter Control we need to make sure that the other control with which this
control works is docked towards the same side of the container. Let's do that with an example.
Assume that we have a TextBox on the form. Drag a Splitter control onto the form. Set the
TextBox's dock property to left. If we want to resize the TextBox once we finish using it set the
Splitter's dock property to left (both the controls should be docked towards the same end). When
the program is executed and when you pass the mouse over the Splitter control it allows us to
resize the TextBox allowing us to move it away from it's current position.
HelpProvider
Providing help with your application is very useful as it allows your users to understand it more
easily, thereby increasing productivity and saving some money. Support for help in Visual Basic
exists and you can display HTML files that can contain a set of linked topics.
Help Class
The Help class allows us to display HTML help to users. The Help class provides two methods:
ShowHelp and ShowHelpIndex. ShowHelp is used to display a help file for a particular control
and requires that control to be displayed along with the help file. The URL you specify for the
help file can be in the form of C:\myHelp (local machine) or
http:\\www.startvbdotnet.com\help.htm (Web). Generally, the Help class is used in conjunction
with Menus, Context Menus.
Example
The following code displays a help file. This code assumes that you have a Button, Button1,
Label, Label1 on the form and a help file named Apphelp.htm in the C: drive of your machine.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
Help.ShowHelp(Label1, "C:\Apphelp.htm")
'using the Help class with label control
End Sub
The ShowHelpIndex method is used to display the index of a specified help file. You call the
ShowHelpIndex method just like you call the ShowHelp method.
HelpProvider Component
HelpProviderComponent allows us to provide help for controls on the form when F1 key is
pressed. The HelpProviderComponent is an extender provider which means that it coordinates
and maintains properties for each control on the form. Notable Property of HelpProvider
component is the HelpNameSpace property which specifies the URL for the help file associated
with it.
The HelpProvider component provides three additional properties to each control on the form.
These properties are:
HelpString: Determines the help string associated with a control.
HelpKeyWord: Determines the help keyword associated with a control.
HelpNavigator: Determines the kind of help associated with a control. Provides six values:
TableOfContents, Find, Index, Topic, AssociatedIndex and KeywordIndex.
The above said three properties are visible in the properties window for each control once the
HelpProvider component is added to the form. If the HelpNameSpace property is not set, the
HelpString is automatically displayed, and other two properties are ignored.
Example
Drag two Buttons and the HelpProvider component onto the form. The following code displays a
help string when Button2 has the focus and F1 key is pressed.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
HelpProvider1.SetHelpString(Button2, "I am supported by HelpProvider1")
'button2 needs to have focus to display this string when F1 is pressed
End Sub
StatusBar
Status Bars are used to display status messages at the bottom of the form. They are generally used
to provide additional information, such as page numbers, display a message, etc. There are two
kinds of status bars: simple status bars and status bars that display a panel. Simple status bars
display a single message on the status bar and a status bar with panels can display multiple
messages. Below is the image of a StatusBar control.
StatusBar Event
Defalut event of the StatusBar control is the PanelClick event which looks like this in Code:
Private Sub StatusBar1_PanelClick(ByVal sender As System.Object, ByVal e
_
As System.Windows.Forms.StatusBarPanelClickEventArgs) Handles
StatusBar1.PanelClick
End Sub
From the toolbox add a status bar control to the form. The following code will display the
message "Hello" on the StatusBar when the form loads.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
StatusBar1.Text = "Hello"
End Sub
You can add panels to a status bar by opening it's properties window and clicking the Panels
property. When you click the Panels property it opens the StatusBarPanel Collection Editor
which looks like the image below.
You add panels by clicking the Add button found in the editor. While adding panels you can set
the Text to be displayed for each panel, an icon, tooltip, width for each panel you add.
To add panels to status bar in code we use the StatusBar.Panel.Add method and
StatusBar.Panels.Remove, StatusBar.Panels.RemoveAt to remove the panels. To access text
in each panel you use the text property of StatusbarPanel as: StatusBarPanels(0).Text="I am
panel one".
To handle status bar panel clicks you use the PanelClick event as shown in the code below. To
work with this code, add a status bar control to the form, open it's properties window, select
the Panels property and add three status bar panels. For StatusBarPanel1 set the text "More VB
.NET? Please Visit ->", for StatusBarPanel2 set the text "MSDN" and for StatusBarPanel3
"Startvbdotnet.com". The form in design view should look like the image below.
NotifyIcon
Notify Icons display an icon in Windows System Tray. This is really useful for processes that run
in the background and don't have their own interface. Since VB allows us to create Windows
Services (services that run in the background and display control panels) now, we can use these
notify icon's to associate funtionality to windows services. You can also use this icon to associate
help with your application, launch another application or anything else which you think can be
appropriate.
The default event associated with Notify Icon is the MouseDown event which looks like this in
code:
Private Sub NotifyIcon2_MouseDown(ByVal sender As System.Object,
ByVal e As _
System.Windows.Forms.MouseEventArgs) Handles NotifyIcon2.MouseDown
End Sub
You can also handle click and double-click events for notify icon. The code sample below works
with the click event of the Notify Icon to display a help file.
To create a Notify Icon component you need an icon (.ico) file to assign to it's Icon property. If
you have an icon then you can use it else you might need to create an icon. You can create new
icons with Visual Studio's icon designer. To open the icon designer select Project->Add New
Item and from the Add New Item dialog select Icon File and click open. You can use the toolbars
that are visible to design your icon. The Icon Designer Window is displayed below.
Sample Code
Drag a Notify Icon component and a Label control from the toolbar onto the form. Open the
properties window for the Notify Icon and set the Icon property to the path of the icon and the
text property to "Help with this Form". This is the icon that will be displayed when you run the
application. The Label control is needed to set the help file. Set the text for label as "I have Help".
The form in design view should look like the image below.
This sample code launches a help file when you click the Icon in System Tray. This sample code
assumes that you have a help file, "Help.htm" in the C: drive of your machine.
Private Sub NotifyIcon1_click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles NotifyIcon1.Click
'handling click event of the NotifyIcon
Help.ShowHelp(Label1, "c:\help.htm")
'using the Help class and it's ShowHelp method to display a help file
End Sub
When you run the application, an icon will be visible in the System Tray and when you click the
icon the help file named "Help.htm" will be launched. The image below displays the output from
above code.
ASP.NET
Asp.Net – Introduction
Asp.net is the new offering for Web developers form the Microsoft. It is not simply the next
generation of ASP. Because it has evolved from Asp, Asp.Net looks very similar to its
predecessor. But concepts like web forms, Web Services, or server controls gives Asp.Net the
power to build real Web application.
What is ASP.NET?
• ASP.NET provides services to allow the creation, deployment, and execution of Web
Applications and Web Services
• Like ASP, ASP.NET is a server-side technology
• Web Applications are built using Web Forms. ASP.NET comes with built-in Web Forms
controls, which are responsible for generating the user interface. They mirror typical
HTML widgets like text boxes or buttons. If these controls do not fit your needs, you are
free to create your own user controls.
• Web Forms are designed to make building web-based applications as easy as building
Visual Basic applications
Features of ASP.NET
When an ASP.NET page runs, the page goes through a life cycle in which it performs a
series of processing steps. These include initialization, instantiating controls, restoring and
maintaining state, running event handler code, and rendering. It is important for you to
understand the page life cycle so that you can write code at the appropriate life-cycle stage for the
effect you intend. Additionally, if you develop custom controls, you must be familiar with the
page life cycle in order to correctly initialize controls, populate control properties with view-state
data, and run any control behavior code. (The life cycle of a control is based on the page life
cycle, but the page raises more events for a control than are available for an ASP.NET page
alone.)
In general terms, the page goes through the stages outlined in the following table. In
addition to the page life-cycle stages, there are application stages that occur before and after a
request but are not specific to a page.
Stage Description
Page request The page request occurs before the page life cycle begins. When the page is
requested by a user, ASP.NET determines whether the page needs to be parsed
and compiled (therefore beginning the life of a page), or whether a cached version
of the page can be sent in response without running the page.
Start In the start step, page properties such as Request and Response are set. At this
stage, the page also determines whether the request is a postback or a new request
and sets the IsPostBack property. Additionally, during the start step, the page's
UICulture property is set.
Page During page initialization, controls on the page are available and each control's
initialization UniqueID property is set. Any themes are also applied to the page. If the current
request is a postback, the postback data has not yet been loaded and control
property values have not been restored to the values from view state.
Load During load, if the current request is a postback, control properties are loaded with
information recovered from view state and control state.
Validation During validation, the Validate method of all validator controls is called, which
sets the IsValid property of individual validator controls and of the page.
Postback event If the request is a postback, any event handlers are called.
handling
Rendering Before rendering, view state is saved for the page and all controls. During the
rendering phase, the page calls the Render method for each control, providing a
text writer that writes its output to the OutputStream of the page's Response
property.
Unload Unload is called after the page has been fully rendered, sent to the client, and is
ready to be discarded. At this point, page properties such as Response and
Request are unloaded and any cleanup is performed.
Life-cycle Events
Within each stage of the life cycle of a page, the page raises events that you can handle to run
your own code. For control events, you bind the event handler to the event, either declaratively
using attributes such as onclick, or in code.
Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with
particular names and automatically runs those methods when certain events are raised. If the
AutoEventWireup attribute of the @ Page directive is set to true (or if it is not defined, since by
default it is true), page events are automatically bound to methods that use the naming
convention of Page_event, such as Page_Load and Page_Init
The following table lists the page life-cycle events that you will use most frequently.
There are more events than those listed; however, they are not used for most page processing
scenarios. Instead, they are primarily used by server controls on the ASP.NET Web page to
initialize and render themselves. If you want to write your own ASP.NET server controls, you
need to understand more about these stages.
Note
If the request is a postback, the values of the controls have not yet been
restored from view state. If you set a control property at this stage, its value
might be overwritten in the next event.
Init Raised after all controls have been initialized and any skin settings have been
applied. Use this event to read or initialize control properties.
InitComplete Raised by the Page object. Use this event for processing tasks that require all
initialization be complete.
PreLoad Use this event if you need to perform processing on your page or control
before the Load event.
After the Page raises this event, it loads view state for itself and all controls,
and then processes any postback data included with the Request instance.
Load The Page calls the OnLoad event method on the Page, then recursively does
the same for each child control, which does the same for each of its child
controls until the page and all controls are loaded.
Use the OnLoad event method to set properties in controls and establish
database connections.
Control events Use these events to handle specific control events, such as a Button control's
Click event or a TextBox control's TextChanged event.
Note
LoadComplete Use this event for tasks that require that all other controls on the page be
loaded.
PreRender Before this event occurs:
• The Page object calls EnsureChildControls for each control and for the
page.
• Each data bound control whose DataSourceID property is set calls its
DataBind method. For more information, see Data Binding Events for
Data-Bound Controls below.
The PreRender event occurs for each control on the page. Use the event to
make final changes to the contents of the page or its controls.
SaveStateComplet Before this event occurs, ViewState has been saved for the page and for all
e controls. Any changes to the page or controls at this point will be ignored.
Use this event perform tasks that require view state to be saved, but that do
not make any changes to controls.
Render This is not an event; instead, at this stage of processing, the Page object calls
this method on each control. All ASP.NET Web server controls have a
Render method that writes out the control's markup that is sent to the
browser.
If you create a custom control, you typically override this method to output
the control's markup. However, if your custom control incorporates only
standard ASP.NET Web server controls and no custom markup, you do not
need to override the Render method.
A user control (an .ascx file) automatically incorporates rendering, so you do
not need to explicitly render the control in code.
Unload This event occurs for each control and then for the page. In controls, use this
event to do final cleanup for specific controls, such as closing control-specific
database connections.
For the page itself, use this event to do final cleanup work, such as closing
open files and database connections, or finishing up logging or other request-
specific tasks.
Note
During the unload stage, the page and its controls have been rendered, so
you cannot make further changes to the response stream. If you attempt to
call a method such as the Response.Write method, the page will throw an
exception.
Structure of Asp.Net
Directives
You can use directives to specify optional settings used by the page compiler when processing
ASP.NET files. For each directive you can set different attributes. One example is the language
directive at the beginning of a page defining the default programming language.
Code declaration blocks are lines of code enclosed in <script> tags. They contain the runat=server
attribute, which tells ASP.NET that these controls can be accessed on the server and on the client.
Optionally you can specify the language for the block. The code block itself consists of the
definition of member variables and methods.
Render blocks contain inline code or inline expressions enclosed by the character sequences
shown here. The language used inside those blocks could be specified through a directive like the
one shown before.
You can declare several standard HTML elements as HTML server controls. Use the element as
you are familiar with in HTML and add the attribute runat=server. This causes the HTML
element to be treated as a server control. It is now programmatically accessible by using a unique
ID. HTML server controls must reside within a <form> section that also has the attribute
runat=server.
There are two different kinds of custom controls. On the one hand there are the controls that ship
with .NET, and on the other hand you can create your own custom controls. Using custom server
controls is the best way to encapsulate common programmatic functionality.Just specify elements
as you did with HTML elements, but add a tag prefix, which is an alias for the fully qualified
namespace of the control. Again you must include the runat=server attribute. If you want to get
programmatic access to the control, just add an Id attribute.You can include properties for each
server control to characterize its behavior. For example, you can set the maximum length of a
TextBox. Those properties might have sub properties; you know this principle from HTML. Now
you have the ability to specify, for example, the size and type of the font you use .The last
attribute is dedicated to event binding. This can be used to bind the control to a specific event
You can create bindings between server controls and data sources. The data binding expression is
enclosed by the character sequences <%# and %>. The data-binding model provided by
ASP.NET is hierarchical. That means you can create bindings between server control properties
and superior data sources.
If you need to create an instance of an object on the server, use server-side object tags. When the
page is compiled, an instance of the specified object is created. To specify the object use the
identifier attribute. You can declare .NET objects using class as the identifier, and COM objects
using either progid or classid.
With server-side include directives you can include raw contents of a file anywhere in your
ASP.NET file. Specify the type of the path to filename with the path type attribute. Use either
File, when specifying a relative path, or Virtual, when using a full virtual path.
Server-side Comments
To prevent server code from executing, use these character sequences to comment it out. You can
comment out full blocks - not just single lines.
Asp.Net – Framework
ASP.NET is based on the fundamental architecture of .NET Framework. Visual studio provides a
uniform way to combine the various features of this Architecture. Architecture is explained form
bottom to top in the following discussion.
At the bottom of the Architecture is Common Language Runtime. NET framework common
language runtime resides on top of the operating system services. The common language runtime
loads and executes code that targets the runtime. This code is therefore called managed code. The
runtime gives you, for example, the ability for cross-language integration.
1..NET Framework provides a rich set of class libraries. These include base classes, like
networking and input/output classes, a data class library for data access, and classes for use by
programming tools, such as debugging services. All of them are brought together by the Services
Framework, which sits on top of the common language runtime.
2. ADO.NET is Microsoft’s ActiveX Data Object (ADO) model for the .NET Framework.
ADO.NET is not simply the migration of the popular ADO model to the managed environment
but a completely new paradigm for data access and manipulation.
ADO.NET is intended specifically for developing web applications. This is evident from its two
major design principles:
>>Disconnected Datasets—In ADO.NET, almost all data manipulation is done outside the
context of an open database connection.
>>Effortless Data Exchange with XML—Datasets can converse in the universal data format of
the Web, namely XML.
3. The 4th layer of the framework consists of the Windows application model and, in parallel, the
Web application model.
The Web application model-in the slide presented as ASP.NET-includes Web Forms and Web
Services. ASP.NET comes with built-in Web Forms controls, which are responsible for
generating the user interface. They mirror typical HTML widgets like text boxes or buttons. If
these controls do not fit your needs, you are free to create your own user controls. Web Services
brings you a model to bind different applications over the Internet. This model is based on
existing infrastructure and applications and is therefore standard-based, simple, and adaptable.
Web Services are software solutions delivered via Internet to any device. Today, that means Web
browsers on computers, for the most part, but the device-agnostic design of .NET will eliminate
this limitation.
4. One of the obvious themes of .NET is unification and interoperability between various
programming languages. In order to achieve this; certain rules must be laid and all the languages
must follow these rules. In other words we can not have languages running around creating their
own extensions and their own fancy new data types. CLS is the collection of the rules and
constraints that every language (that seeks to achieve .NET compatibility) must follow.
5.The CLR and the .NET Frameworks in general, however, are designed in such a way that code
written in one language can not only seamlessly be used by another language. Hence ASP.NET
can be programmed in any of the .NET compatible language whether it is VB.NET, C#, Managed
C++ or JScript.NET.
Asp.Net – Controls
Types of Controls:
1. Web Controls
2. Html Controls
3. Validation Controls
4. User Controls
1. Web Controls:
Web Controls provide a more consistent object model and a higher level of abstraction than
HtmlControls
– Most HTML elements can also be represented as Web Controls on the server
– Web Control versions typically have a more consistent interface (background color is always
Back Color property whereas in HTML it may be a style attribute (span) or a property (table) )
– Web Controls also provide higher-level controls with more functionality than primitive HTML
elements (like the Calendar control)
– Web Controls may render themselves differently based on client browser capabilities
Web controls
Button DropDownList
Calendar ListBox
CheckBox Panel
RadioButton Table
HyperLink TableRow
Textbox TableCell
<html>
<body>
<form runat="Server">
</form>
</body>
</html>
AdRotator
The AdRotator is a special control in ASP.NET that is used to display flashing banner ads. The
control is capable of displaying ads randomly or sequentially as set by the user. Each time the
page is refreshed or reloaded a new ad can be displayed to the user. Also, we can assign priorities
in such a way that certain ads are displayed frequently than others. The class hierarchy for this
control is as follows:
Object
Control
WebControl
AdRotator
AdvertisementFile
KeywordFilter
Target
AdvertisementFile
The AdvertisementFile property specifies the path to an Advertisement File. The Advertisement
file is a well-formed XML document that contains information for the image that needs to be
displayed and the page to which the user should be redirected when he clicks the ad. The syntax
for the Advertisement file is as follows:
ImageUrl: Specifies the image URL that presents the image for the advertisement
NavigateUrl: Specifies the URL of the page to which the user should be taken to when he clicks
on the image
AlternateText: An optional parameter that specifies the text when the user moves his mouse
pointer over the image
Keyword: Optional parameter that specifies the keyword (category) like books, programming, etc
Impressions: Optional parameter that provides a number that indicates the weight of the ad in the
order of rotation with respect to other ads in the file
KeywordFilter
The KeywordFilter property specifies a keyword to filter for specific types of advertisements in
the XML advertisement file. Each advertisement in the XML advertisement file can be assigned a
category keyword. The KeywordFilter property filters the advertisements for the specified
keyword. Only advertisements containing the keyword will be selected for the AdRotator control
and it is not possible to specify more than one keyword in the KeywordFilter property, nor it is
possible to declare multiple keywords in the advertisement file.
Target
The Target property specifies the name of the browser window or frame that displays the contents
of the Web page linked to when the AdRotator control is clicked. This property can also take the
following HTML frame-related keywords.
2.HTML Controls:
– Any HTML element in an ASPX page marked with the runat=server attribute will become an
HTML control on the server
– HTML elements with no distinguished server-side functionality (like div, span, etc.) are all
represented as HtmlGenericControl instances
Html Controls
<html>
<body>
<form runat="Server">
</form>
</body>
</html>
ASP.NET server controls are reusable components that can perform the same work as traditional
HTML controls, but have the additional benefit of being "programmable objects". In other words,
they can be programmatically accessed, just like any other .NET object or class, respond to
events, get/set properties, and do all the other things objects do. ASP.NET server controls use a
tag-like syntax for declaring the various controls used on a web page -- for example:
One of the unique qualities of ASP.NET server controls is that, even though their tag syntax is
different from HTML's, every ASP.NET server control is rendered to standard HTML after being
processed on the server, thus abstracting the functionality of the entire HTML control set.
Additional ASP.NET server controls, provide the ability to render rich web content
The validator controls are the main elements of the solution. A validator is a visual ASP.NET
control that checks a specific validity condition of another control. It generally appears to the user
as a piece of text that displays or hides depending on whether the control it is checking is in error.
It can also be an image, or can even be invisible and still do useful work. There are six types of
validator controls that perform different types of checks.
Requiredfield validator:
The RequiredFieldValidator control validates input by verifying that the corresponding field isn’t
blank. It’s perfect for TextBoxes representing required fields in a form, because if any of those
TextBoxes is blank, the RequiredFieldValidator won’t allow the form to be submitted to the
server.
Because required fields are so common in Web forms, RequiredFieldValidator has the potential
to see more use than all the other validation controls combined. It’s often used in conjunction
with other validation controls because none of the others run their validation checks on blank
fields.
RangeValidator
The RangeValidator control is the answer to the question “How do I ensure that an input value
falls within a specified range?” Suppose you ask the user to type in a percentage, and that valid
values range from 0 to 100, inclusive. Here’s how to reject any numbers that fall outside that
range:
MaximumValue="12/31/2002"
Type="Date"
ErrorMessage="Date out of range"
Display="static"
Color="red"
RunAt="server"
/>
Compare Validator
The CompareValidator control validates input by comparing it to a constant value specified with
a ValueToCompare attribute or to a value in another control identified with a ControlToCompare
attribute. ControlToCompare makes CompareValidator a valuable control for validating input
based on other input. Suppose you invite the user to enter minimum and maximum values
denoting both ends of a range. It doesn’t make sense to accept a maximum that’s less than the
minimum, so you can use a CompareValidator to ensure the integrity of the input. In the
following example, the validator signals an error if the maximum is less than the minimum. The
Operator attribute specifies that the value entered in the TextBox named “Maximum”
must be equal to or greater than the value entered into the TextBox named “Minimum.” The Type
attribute identifies the type of data involved in the comparison:
Other supported values for Operator are Equal, NotEqual, GreaterThan, LessThan,
LessThanEqual, and DataTypeCheck. The last of these validates the type of data entered by
verifying that it matches the type specified in the Type attribute. If you simply wanted to verify
that the user input an integer, for example, you could set Type to Integer and Operator to
DataTypeCheck.
RegularExpressionValidator
The most versatile validation control by far is the RegularExpressionValidator, which validates
input by verifying that it conforms to a format specified in a regular expression. You can use
RegularExpressionValidator to perform a variety of common validation chores, from verifying
that an input value contains only numbers to ensuring that e-mail addresses, zip codes, and credit
card numbers are well-formed. Here’s a very simple example—one that uses a
RegularExpressionValidator to reject input containing non-numeric characters:
ErrorMessage="Digits only"
Display="static"
Color="red"
RunAt="server"
/>
In a regular expression, \d represents the digits 0-9 and + means “one or more of.” The expression
\d+ means “one or more characters that are digits.” If the user tries to slip in a string with a letter
in it, the validator will reject it.
ValidationSummary
<asp:RegularExpressionValidator
ControlToValidate="Password"
ValidationExpression=".{8,}"
Display="static"
ErrorMessage="The password must contain at least 8 characters"
RunAt="server"
/>
<asp:ValidationSummary
DisplayMode="BulletList"
HeaderText="This page contains the following errors"
Display="static"
RunAt="server"
/>
The ValidationSummary control’s DisplayMode attribute can be set to BulletList, which displays
error messages in a bulleted list; List, which displays error messages in a list without bullets; or
SingleParagraph, which displays error messages without bullets or line breaks. HeaderText
specifies the text, if any, that appears above the error messages. A ValidationSummary control’s
ShowMessageBox and ShowSummary properties can be used to further customize the control’s
output. By default, ShowMessageBox is false and ShowSummary is true, meaning that error
messages are displayed in the Web page. However, setting ShowMessageBox to true and
ShowSummary to false displays the error messages in a pop-up message box (what JavaScript
programmers refer to as an alert box because of the JavaScript command used to display it: alert):
<asp:ValidationSummary
DisplayMode="BulletList"
HeaderText="This page contains the following errors"
ShowMessageBox="true"
ShowSummary="false"
RunAt="server"
/>
Setting both ShowMessageBox and ShowSummary to true causes the validation summary to
appear in a message box and in the Web page.
CustomValidator
When none of the other validators fits the bill, CustomValidator will do the job that no others can.
As its name implies, CustomValidator validates input using an algorithm that you supply. If you
want CustomValidator to check input on the client side, you provide a JavaScript function to do
the checking and identify the function with a ClientValidationFunction attribute. (You can use
VBScript if you’d like, but realize that doing so sacrifices compatibility with browsers other than
Internet Explorer.) If you want the input checked on the server as well, you provide the validation
function and identify it with an OnServerValidate attribute. The following example uses
CustomValidator to verify that an input value is an even multiple of 10:
-->
</script>
<script language="C#" runat="server">
The key is to set args.IsValid to true or false on the client side and e.IsValid to true or false on the
server side to indicate whether the input is valid. CustomValidator can be used to apply any
validation algorithm you want as long a you’re willing to write the code to back it up.
Data Binding
Data binding is binding controls to data from databases. With data binding we can bind a
control to a particular column in a table from the database or we can bind the whole table to the
data grid. Data binding provides simple, convenient, and powerful way to create a read/write link
between the controls on a form and the data in their application.
ArrayList
The ArrayList object is a collection of items containing a single data value.Items are added to the
ArrayList with the Add() method. The following code creates a new ArrayList object named
mycountries and four items are added:
if Not Page.IsPostBack then
dim mycountries=New ArrayList
mycountries.Add("Norway")
mycountries.Add("Sweden")
mycountries.Add("France")
mycountries.Add("Italy")
end if
An ArrayList can also be sorted alphabetically or numerically with the Sort() method:
if Not Page.IsPostBack then
dim mycountries=New ArrayList
mycountries.Add("Norway")
mycountries.Add("Sweden")
mycountries.Add("France")
mycountries.Add("Italy")
mycountries.TrimToSize()
mycountries.Sort()
end if
To sort in reverse order, apply the Reverse() method after the Sort() method:
The Hashtable object contains items in key/value pairs. The keys are used as indexes, and very
quick searches can be made for values by searching through their keys.Items are added to the
Hashtable with the Add() method.The following code creates a Hashtable named mycountries and
four elements are added:
if Not Page.IsPostBack then
dim mycountries=New Hashtable
mycountries.Add("N","Norway")
mycountries.Add("S","Sweden")
mycountries.Add("F","France")
mycountries.Add("I","Italy")
end if
A Hashtable object may automatically generate the text and values to the following controls:
• asp:RadioButtonList
• asp:CheckBoxList
• asp:DropDownList
• asp:Listbox
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New Hashtable
mycountries.Add("N","Norway")
mycountries.Add("S","Sweden")
mycountries.Add("F","France")
mycountries.Add("I","Italy")
rb.DataSource=mycountries
rb.DataValueField="Key"
rb.DataTextField="Value"
rb.DataBind()
end if
end sub
sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
end sub
</script>
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
<p><asp:label id="lbl1" runat="server" /></p>
</form>
</body>
</html>
The SortedList Object
The SortedList object contains items in key/value pairs. A SortedList object automatically sort
the items in alphabetic or numeric order.Items are added to the SortedList with the Add() method.
if Not Page.IsPostBack then
dim mycountries=New SortedList
mycountries.Add("N","Norway")
mycountries.Add("S","Sweden")
mycountries.Add("F","France")
mycountries.Add("I","Italy")
end if
An XML File
When a Web application runs, ASP.NET maintains information about the current application,
each user session, the current HTTP request, the requested page, and so on. ASP.NET contains a
series of classes to encapsulate this context information.
ASP.NET makes instances of these classes available as intrinsic objects that you can access from
your code. The following table lists these intrinsic objects and the classes they are instances of.
Response
Provides access to the output stream for the current page. You can use this class to inject text into
the page, to write cookies, and more.
Request
Provides access to the current page request, including the request headers, cookies, client
certificate, query string, and so on. You can use this class to read what the browser has sent
Context
Provides access to the entire current context (including the request object). You can use this class
to share information between pages.
Server
Exposes utility methods that you can use to transfer control between pages, get information about
the most recent error, encode and decode HTML text, and more.
Application
Provides access to application-wide methods and events for all sessions. Also provides access to
an application-wide cache you can use to store information.
Session
Provides information to the current user session. Also provides access to a session-wide cache
you can use to store information, along with the means to control how the session is managed.
Trace
Provides a way to display both system and custom trace diagnostic messages in the HTTP page
output.
Cookies Overview
Cookies provide a means in Web applications to store user-specific information. For example,
when a user visits your site, you can use cookies to store user preferences or other information.
When the user visits your Web site another time, the application can retrieve the information it
stored earlier.
A cookie is a small bit of text that accompanies requests and pages as they go between the Web
server and browser. The cookie contains information the Web application can read whenever the
user visits the site.
For example, if a user requests a page from your site and your application sends not just a page,
but also a cookie containing the date and time, when the user's browser gets the page, the browser
also gets the cookie, which it stores in a folder on the user's hard disk.
Later, if user requests a page from your site again, when the user enters the URL the browser
looks on the local hard disk for a cookie associated with the URL. If the cookie exists, the
browser sends the cookie to your site along with the page request. Your application can then
determine the date and time that the user last visited the site. You might use the information to
display a message to the user or check an expiration date.
Cookies are associated with a Web site, not with a specific page, so the browser and server will
exchange cookie information no matter what page the user requests from your site. As the user
visits different sites, each site might send a cookie to the user's browser as well; the browser
stores all the cookies separately.
Cookies help Web sites store information about visitors. More generally, cookies are one way of
maintaining continuity in a Web application—that is, of performing state management. Except
for the brief time when they are actually exchanging information, the browser and Web server are
disconnected. Each request a user makes to a Web server is treated independently of any other
request. Many times, however, it's useful for the Web server to recognize users when they request
a page. For example, the Web server on a shopping site keeps track of individual shoppers so the
site can manage shopping carts and other user-specific information. A cookie therefore acts as a
kind of calling card, presenting pertinent identification that helps an application know how to
proceed.
Cookies are used for many purposes, all relating to helping the Web site remember users. For
example, a site conducting a poll might use a cookie simply as a Boolean value to indicate
whether a user's browser has already participated in voting so that the user cannot vote twice. A
site that asks a user to log on might use a cookie to record that the user already logged on so that
the user does not have to keep entering credentials.
You can add cookies to the Cookies collection in a number of ways. The following example
shows two methods to write cookies:
Visual Basic
Response.Cookies("userName").Value = "patrick"
Response.Cookies("userName").Expires = DateTime.Now.AddDays(1)
C#
Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
The example adds two cookies to the Cookies collection, one named userName and the other
named lastVisit. For the first cookie, the values of the Cookies collection are set directly.
Reading Cookies
Visual Basic
If Not Request.Cookies("userName") Is Nothing Then
Label1.Text = Server.HtmlEncode(Request.Cookies("userName").Value)
End If
C#
if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
if(Request.Cookies["userName"] != null)
{
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text = Server.HtmlEncode(aCookie.Value);
}
ASP.NET session state enables you to store and retrieve values for a user as the user navigates
the different ASP.NET pages that make up a Web application. HTTP is a stateless protocol,
meaning that your Web server treats each HTTP request for a page as an independent request; the
server retains no knowledge of variable values used during previous requests. ASP.NET session
state identifies requests from the same browser during a limited time window as a session, and
provides the ability to persist variable values for the duration of that session.
Session Variables
By default, session variables can be any valid .NET type. For example, the following code
example stores an ArrayList of values in a session variable named "StockPicks." Note that the
value returned by the "StockPicks" session variable must be cast as the appropriate type upon
retrieval from the SessionStateItemCollection.
View State Overview
A Web application is stateless. A new instance of the Web page class is created each time the
page is requested from the server. This would ordinarily mean that all information associated with
the page and its controls would be lost with each round trip. For example, if a user enters
information into a text box on an HTML Web page, that information is sent to the server, but is
not returned to the client. To overcome this inherent limitation of Web programming, the
ASP.NET page framework includes several state-management features, one of which is view
state, to preserve page and control values between round trips to the Web server.
View state is the method that the ASP.NET page framework uses by default to preserve page and
control values between round trips. When the HTML for the page is rendered, the current state of
the page and values that need to be retained during postback are serialized into base64-encoded
strings and output in the view state hidden field or fields.
ADO .NET
Most applications need data access at one point of time making it a crucial component when
working with applications. Data access is making the application interact with a database, where
all the data is stored. Different applications have different requirements for database
access. ASP.NET uses ADO .NET (Active X Data Object) as it's data access and manipulation
protocol which also enables us to work with data on the Internet.
Advantages of ADO.Net
Data Access in ADO.NET relies on two components: DataSet and Data Provider.
DataSet
Data Provider
The Data Provider is responsible for providing and maintaining the connection to the database. A
DataProvider is a set of related components that work together to provide data in an efficient and
performance driven manner. The .NET Framework currently comes with two DataProviders: the
SQL Data Provider which is designed only to work with Microsoft's SQL Server 7.0 or later and
the OleDb DataProvider which allows us to connect to other types of databases like Access and
Oracle. Each DataProvider consists of the following component classes:
A connection object establishes the connection for the application with the database. The
command object provides direct execution of the command to the database. If the command
returns more than a single value, the command object returns a DataReader to provide the data.
Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated
using the command object or the DataAdapter.
The Connection object creates the connection to the database. Microsoft Visual Studio .NET
provides two types of Connection classes: the SqlConnection object, which is designed
specifically to connect to Microsoft SQL Server 7.0 or later, and the OleDbConnection object,
which can provide connections to a wide range of database types like Microsoft Access and
Oracle. The Connection object contains all of the information required to open a connection to the
database.
ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE or
DELETE
ExecuteScalar: Returns a single value from a database query
ExecuteReader: Returns a result set by way of a DataReader object
The DataReader object provides a forward-only, read-only, connected stream recordset from a
database. Unlike other components of the Data Provider, DataReader objects cannot be directly
instantiated. Rather, the DataReader is returned as the result of the Command object's
ExecuteReader method. The SqlCommand.ExecuteReader method returns a SqlDataReader
object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object. The
DataReader can provide rows of data directly to application logic when you do not need to keep
the data cached in memory. Because only one row is in memory at a time, the DataReader
provides the lowest overhead in terms of system performance but requires the exclusive use of an
open Connection object for the lifetime of the DataReader.
The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is essentially
the middleman facilitating all communication between the database and a DataSet. The
DataAdapter is used either to fill a DataTable or DataSet with data from the database with it's Fill
method. After the memory-resident data has been manipulated, the DataAdapter can commit the
changes to the database by calling the Update method. The DataAdapter provides four properties
that represent database commands:
SelectCommand
InsertCommand
DeleteCommand
UpdateCommand
When the Update method is called, changes in the DataSet are copied back to the database and
the appropriate InsertCommand, DeleteCommand, or UpdateCommand is executed.
The DataAdapter Configuration wizard let's you customize your data adapter as you want, like
displaying the whole table or displaying selected columns from the table and so on. To start, open
a new database in Access, name it as books, create a table, Table1 with some fields in it and save
the database in the C: drive of your machine. To start creating your own DataAdapter, open a
blank form and add a button (Button1) and a DataGrid control to it from the toolbox. Our
intention here is to display the table or some columns in the table which we created in Access in
the DataGrid control when Button1 is clicked. To do that, click on the Data tab in the toolbox and
double-click OleDbDataAdapter object. We are using OleDbDataAdapter here as we are working
with an OleDb data source. After you select OleDbDataAdapter from the data tab in the toolbox it
gets added to the component tray beneath the Web Forms designer and opens the Data Adapter
Configuration wizard dialog box which looks like the image below.
Click the Next> button in the Data Adapter Configuration wizard to select the data connection
you want to use. The dialog box that opens up look like the image below.
Since we are working with our own table, select the New Connection button in that dialog box
which opens up the Data Link properties dialog. The Data Link Properties dialog looks like the
image below.
In the Data Link properties dialog click the Provider tab and select "Microsoft Jet 4.0 OLE DB
Provider" from the list of available providers. After selecting the provider from the Provider tab
click Next> button to take you to the Connection tab. Click on the ellipse where it says "Select or
enter a database name" and browse for the database on the local drive. Since we are working with
our own database (Books.mdb) located on the C: drive, select that. Click on the "Test
Connection" button to test the connection and if the connection succeeds, click OK. Clicking OK
displays a dialog box like the image below.
It's here where we will generate the SQL Statement we use with this data adapter. Click next on
this dialog box which takes you to another dialog like the image below.
It's here where we build our SQL Queries. To build your query click the Query Builder button on
this dialog. Once you click that button, the Query Builder dialog opens with a list that displays all
the tables in the database with which we are working. In this case it displays only one table as we
created only one table in the books database. The Query Builder dialog looks like the image
below. Select Table1 in this dialog and click Add to add Table1 to the Query Builder dialog. You
can select entire table to be displayed in the DataGrid or just some columns. To display entire
table in the DataGrid select the checkbox named "All Columns" in the small dialog named
"Table1" which automatically builds the SQL statement for us. If you want to display specific
columns from the table in the DataGrid, check on the columns you want to display. Once you
finish with that, click next.
The dialog that opens when you click next looks like the image below.
This dialog lists the configuration of the data adapter and lists the results. Click finish to close the
Data Adapter Configuration wizard.
An application typically needs to perform one or more select, insert, update, or delete queries to a
SQL database. The following table shows an example of each of these queries.
Query Example
Simple Select SELECT * from Employees WHERE FirstName =
'Bradley';
Join Select SELECT * from Employees E, Managers M
WHERE E.FirstName = M.FirstName;
Insert INSERT into Employees VALUES ('123-45-
6789','Bradley','Millington','Program Manager');
Update UPDATE Employees SET Title = 'Development
Lead' WHERE FirstName = 'Bradley';
Delete DELETE from Employees WHERE Productivity <
10;
To give your page access to the classes you will need to perform SQL data access, you must
import the System.Data and System.Data.SqlClient namespaces into your page.
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
To perform a select query to a SQL database, you create a SqlConnection to the database passing
the connection string, and then construct a SqlDataAdapter object that contains your query
statement. To populate a DataSet object with the results from the query, you call the command's
Fill method.
SqlConnection myConnection = new
SqlConnection("server=(local)\NetSDK;database=pubs;Trusted_Connection=yes");
SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);
The benefit of using a dataset is that it gives you a disconnected view of the database. You can
operate on a dataset in your application, and then reconcile your changes with the actual database
later. For long-running applications this is often the best approach. For Web applications, you are
usually performing short operations with each request (commonly to simply display the data).
You often don't need to hold a DataSet object over a series of several requests. For situations like
these, you can use a SqlDataReader.
A SqlDataReader provides a forward-only, read-only pointer over data retrieved from a SQL
database. To use a SqlDataReader, you declare a SqlCommand instead of a SqlDataAdapter.
The SqlCommand exposes an ExecuteReader method that returns a SqlDataReader.
myConnection.Open();
SqlDataReader dr = myCommand.ExecuteReader();
...
myConnection.Close();
When performing commands that do not require data to be returned, such as inserts, updates, and
deletes, you also use a SqlCommand. The command is issued by calling an ExecuteNonQuery
method, which returns the number of rows affected. Note that the connection must be explicitly
opened when you use the SqlCommand; the SqlDataAdapter automatically handles opening the
connection for you.
SqlConnection myConnection = new
SqlConnection("server=(local)\NetSDK;database=pubs;Trusted_Connection=yes");
SqlCommand myCommand = new SqlCommand(
"UPDATE Authors SET phone='(800) 555-5555' WHERE au_id = '123-45-6789'",
myConnection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
The SqlDataAdapter maintains a Parameters collection that can be used to replace variable
identifiers (denoted by an "@" in front of the name) with values. You add a new SqlParameter
to this collection that specifies the name, type, and size of the parameter, and then set its Value
property to the value of the select.
myCommand.SelectCommand.Parameters.Add(new SqlParameter("@State",
SqlDbType.NVarChar, 2));
myCommand.SelectCommand.Parameters["@State"].Value = MySelect.Value;
In general, performing ad hoc queries comes at the expense of performance. Using stored
procedures can reduce the cost of performing heavy database operations in an application. A
stored procedure is easy to create, and can even be done using a SQL statement. The following
code example creates a stored procedure that simply returns a table.
CREATE Procedure GetAuthors AS
SELECT * FROM Authors
return
GO
You can create stored procedures that accept parameters as well. For example:
CREATE Procedure LoadPersonalizationSettings (@UserId varchar(50)) AS
SELECT * FROM Personalization WHERE UserID=@UserId
return
GO
Using a stored procedure from an ASP.NET page is just an extension of what you've learned so
far about the SqlCommand object. The CommandText is just the name of the stored procedure
instead of the ad hoc query text. You indicate to the SqlCommand that the CommandText is a
stored procedure by setting the CommandType property.
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
Authentication
Authentication is the means by which you obtain the Identity of the User by validating their
credentials against a known Authority, ie: Active Directory, Database Store, Microsoft Passport
Account etc. If the credentials can't be validated then the Authentication process fails and the
User will assume the Identity of IUSR_Anonymous. Remember that the Web is anonymous by
nature, so they only way to determine who a particular visitor is to authenticate them by having
them provide user credentials (a username/password, usually).
The authentication option for the ASP.NET application is specified by using the tag in the
Web.config file, as shown below:
2. FORMS AUTHENTICATION
You, as a Web application developer, are supposed to develop the Web page and authenticate the
user by checking the provided user ID and password against some user database
3.PASSPORT AUTHENTICATION
A centralized service provided by Microsoft, offers a single logon point for clients.
Unauthenticated users are redirected to the Passport site
4. NONE/CUSTOM AUTHENTICATION:
If we don’t want ASP.NET to perform any authentication, we can set the authentication mode to
“none”.
The reason behind this decision could be:
We don’t want to authenticate our users, and our Web site is open for all to use.
We want to provide our own custom authentication
Webservices are services exposed over the internet. Typically, webservice is just like any other
class library, written in any language. What make it a 'web service' is, it can be accessed across
internet.
Eventhough webservice is a new technology with a wide range of usage, it is a pretty simple
concept. It doesn't require much additional knowledge to create webservices if you are already
familiar with C# or VB.NET. (Web services are not specific to .NET. Even Java has web service
applications, but here we are discussing only the .NET web services.)
As we mentioned, web services are exposed over internet. To make this happen, it has to be
hosted with a web site. Othen than hosted as part of a web site to make this visible across internet,
web services have no web pages or UI. It is just a set of classes with public/private methods and
properties.
Web services are a group of [web] methods. Consumer applications can treat this as just another
class library. Regular class libraries are located along with the same application and we can call
any methods in the class libraries (assemblies). But in case of web services, the assembly is
located in the internet server. The consumer application will not have direct access to the
assembly. Consumer applications have to add a reference to the webservice URL and then call
methods in it. The method call goes across the internet using SOAP protocal and results are
returned across internet in the form of XML. The communication across internet happens
transparently and the application need not know anything about this communication.
If you are using VS.NET, it won't take more than 2-3 minutes to create your first webservice.
Follow the steps below to create a web service:
* Choose New Project from VS.NET and create a C# project of type 'ASP.NET Web Service'
and give the name 'MyWebService'
* The new project will have a default page 'Service1.asmx'. This is your first web service page.
Web service pages have the extension .asmx (like ASP.NET pages have the extension .aspx)
* The code behind file 'Service1.asmx.cs' have a class 'Service1'. This is like other regular classes
with the only difference that it inherits the system class System.Web.Services.WebService. This
is required for web service classes.
* VS.NET creates a sample method for you. All you have to do is, uncomment the following
method in Service1.asmx.cs
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
Note that this method is pretty much same as any other regular method. The only difference is, it
has an attribute [WebMethod]. This attribute make the method visible across internet. If you
remove this attribute, your application will still compile, but the consumer applications cannot
call this method across internet.
Ok, thats all you have to do to create a simple webservice. Build your solution and your web
service is ready to be called by other applications.
A wide range of applications can consume the web services, including web page, other web
services, windows applications etc. let us create a sample windows application and call our web
service.
If you have given a different name fro the project or if you have changed the default service
name, then your URL may differ. Type the URL and press enter. It will attempt to connect with
the web service and if succeded it will retrieve the public web methods and display. Once you get
this success screen, press the 'Add Reference' button on the screen to add the web reference to
your application. There is a space to specify the 'web reference name', which will have the default
value 'localhost'. Leave it as it is.
Now you are ready to make calls to the webservice. Just use the following code in your
application:
localhost.Service1 service = new localhost.Service1();
MessageBox.Show( result );
Let us analyze our code. The first line creates an instance of the Service1 class, just like any
regular class. Only thing is it uses the namespace 'localhost'. This is same as the 'web reference
name' we specified while adding the web reference. We can use any web reference name when
we add the reference and have to use the same name as namespace while making calls to the web
service class.
In the second line, we are actually calling the web method 'HelloWorld()' and it returns the result
as a string. Note this is just like any other method call. So, your application makes the call to web
service as if it is calling any local class library calls!! The communication with web service,
wrapping your calls in SOAP/XML, retrieve results from web service, unwrap the SOAP/XML to
get the actual result etc are done behind the scene by the framework and you need not do any
additional work to make all this work.
Now you can go back to your web service, add more methods with different parameters and play
around with that. You will be able to call methods in the web service just like you use any local
class. Note that when you make any changes to the method name or parameters, or if you add
new methods, you will need to refresh your web reference to get access to the updated web
service methods. To do this, go to the Server Explorer, right click on the web reference name
'localhost' under the 'Web References'. Then choose 'Refresh'. This will communicate with the
web service again and retrieve the latest web service data.
To make calls to any classes, your application need to know the details of the class. To
successfully compile your code, it has to have information about the class, what are the public
methods and properties etc. But in your sample code which calls the web service, the actual
Service1 class resides in the web (in your case, in your local web server). So how does the
application compile without having the 'Service1' class in your application?
This is where the framework help you. When you add a 'web reference' to the web service URL,
VS.NET actually creates local proxy in your application. A local proxy is a minimal version of
the actual class. The proxy has just the sufficient information about the 'real class', which is
required for your application to successfully compile. The proxy class has the list of all public
web methods in the real web service class and it knows the parameters and their data types of
each method.
The most important thing is, your application is actually using this proxy class and not the real
web service class.
localhost.Service1 service = new localhost.Service1();
string result = service.HelloWorld();
MessageBox.Show( result );
In the above code, localhost.Service1 is actually the proxy class (a representative of a real class),
which is created automatically by VS.NET when you added the web reference. You are creating
an instance of the proxy class and calling the 'HelloWorld()' method of this proxy. Since the
proxy class knows that it is 'only a proxy of the real class', it redirects all calls to the 'real web
service class'. The method 'HelloWorld()' in the proxy class takes care of converting the call to a
web request using SOAP/XML. After retrieving the result of the web request to the real web
service class, this proxy class takes the responsibility of parsing the SOAP/XML response and
returning only the result string to the calling applicationn. So the proxy class does all the dirty job
for you.
The proxy class has no implementaion of the functionality. It just redirects the call to the web
service. So, if you make any changes to the implementation in the web service, still you will get
the 'updated result' when you make calls to web service. But, if you change the method name, or
change the parameter types in the web service and do not 'refresh the web reference', then your
application will compile with the old proxy. But when the proxy redirect the call to the web
service, it will find that the parameters or method names do not match and it will fail. So, if there
is any change in the method names or parameters, you must refresh your web reference.