Anda di halaman 1dari 23

Exception handling

Exception handling is an in built mechanism in .NET framework to detect and handle run time
errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies
that occur during the execution of a program. They can be because of user, logic or system
errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET
run time environment provide a default mechanism, which terminates the program execution.

C# provides three keywords try, catch and finally to do exception handling. The try encloses
the statements that might throw an exception whereas catch handles an exception if one exists.
The finally can be used for doing any clean up process.

The general form try-catch-finally in C# is shown below


try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}

If any exception occurs inside the try block, the control transfers to the appropriate catch block
and later to the finally block.

But in C#, both catch and finally blocks are optional. The try block can exist either with one or
more catch blocks or a finally block or with both catch and finally blocks.

If there is no exception occurred inside the try block, the control directly transfers to finally block.
We can say that the statements inside the finally block is executed always. Note that it is an error
to transfer control out of a finally block by using break, continue, return or goto.

In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate
base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or
even the user can create their own exception classes, provided that this should inherit from either
Exception class or one of the standard derived classes of Exception class like
DivideByZeroExcpetion ot ArgumentException etc.

Uncaught Exceptions
The following program will compile but will show an error during execution. The division by zero is
a runtime anomaly and program terminates with an error message. Any uncaught exceptions in
the current context propagate to a higher context and looks for an appropriate catch block to
handle it. If it can't find any suitable catch blocks, the default mechanism of the .NET runtime will
terminate the execution of the entire program.
using System;
class MyClient
{
public static void Main()
{int x = 0;
int div = 100/x;
Console.WriteLine(div);
}}
The modified form of the above program with exception handling mechanism is as follows. Here
we are using the object of the standard exception class DivideByZeroException to handle the
exception caused by division by zero.
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("This line in not executed");
}
catch(DivideByZeroException de)
{
Console.WriteLine("Exception occured");
}
Console.WriteLine("Result is {0}",div);
}
}

In the above case the program do not terminate unexpectedly. Instead the program control
passes from the point where exception occurred inside the try block to the catch blocks. If it finds
any suitable catch block, executes the statements inside that catch and continues with the normal
execution of the program statements.
If a finally block is present, the code inside the finally block will get also be executed.
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{
Console.WriteLine("Exception occured");
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}

Remember that in C#, the catch block is optional. The following program is perfectly legal in C#.
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}

But in this case, since there is no exception handling catch block, the execution will get
terminated. But before the termination of the program statements inside the finally block will get
executed. In C#, a try block must be followed by either a catch or finally block.

Multiple Catch Blocks


A try block can throw multiple exceptions, which can handle by using multiple catch blocks.
Remember that more specialized catch block should come before a generalized one. Otherwise
the compiler will show a compilation error.

//C#: Exception Handling: Multiple catch


using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{
Console.WriteLine("DivideByZeroException" );
}
catch(Exception ee)
{
Console.WriteLine("Exception" );
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}
Catching all Exceptions
By providing a catch block without a brackets or arguments, we can catch all exceptions occurred
inside a try block. Even we can use a catch block with an Exception type parameter to catch all
exceptions happened inside the try block since in C#, all exceptions are directly or indirectly
inherited from the Exception class.

//C#: Exception Handling: Handling all exceptions


using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch
{
Console.WriteLine("oException" );
}
Console.WriteLine("Result is {0}",div);
}
}

The following program handles all exception with Exception object.

//C#: Exception Handling: Handling all exceptions


using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(Exception e)
{
Console.WriteLine("oException" );
}
Console.WriteLine("Result is {0}",div);
}
}

Throwing an Exception
In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this
purpose. The general form of throwing an exception is as follows.

throw exception_obj;
For example the following statement throw an ArgumentException explicitly.

throw new ArgumentException("Exception");

//C#: Exception Handling:


using System;
class MyClient
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception" );
}
Console.WriteLine("LAST STATEMENT");
}
}

Re-throwing an Exception
The exceptions, which we caught inside a catch block, can re-throw to a higher context by using
the keyword throw inside the catch block. The following program shows how to do this.

//C#: Exception Handling: Handling all exceptions


using System;
class MyClass
{
public void Method()
{
try
{
int x = 0;
int sum = 100/x;
}
catch(DivideByZeroException e)
{
throw;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
try
{
mc.Method();
}
catch(Exception e)
{
Console.WriteLine("Exception caught here" );
}
Console.WriteLine("LAST STATEMENT");
}
}

Standard Exceptions
There are two types of exceptions: exceptions generated by an executing program and
exceptions generated by the common language runtime. System.Exception is the base class for
all exceptions in C#. Several exception classes inherit from this class including
ApplicationException and SystemException. These two classes form the basis for most other
runtime exceptions. Other exceptions that derive directly from System.Exception include
IOException, WebException etc.

The common language runtime throws SystemException. The ApplicationException is thrown by


a user program rather than the runtime. The SystemException includes the
ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch
SystemExceptions nor is it good programming practice to throw SystemExceptions in our
applications.

System.OutOfMemoryException
System.NullReferenceException
Syste.InvalidCastException
Syste.ArrayTypeMismatchException
System.IndexOutOfRangeException
System.ArithmeticException
System.DevideByZeroException
System.OverFlowException

User-defined Exceptions
In C#, it is possible to create our own exception class. But Exception must be the ultimate base
class for all exceptions in C#. So the user-defined exception classes must inherit from either
Exception class or one of its standard derived classes.

//C#: Exception Handling: User defined exceptions


using System;
class MyException : Exception
{
public MyException(string str)
{
Console.WriteLine("User defined exception");
}
}
class MyClient
{
public static void Main()
{
try
{
throw new MyException("RAJESH");
}
catch(Exception e)
{
Console.WriteLine("Exception caught here" + e.ToString());
}
Console.WriteLine("LAST STATEMENT");
}
}
Event-driven programming model
ASP.NET Web pages bring to Web applications the familiar model of writing event handlers for
events that occur on either the client or server. The ASP.NET page framework abstracts this
model in such a way that the underlying mechanism of capturing an event on the client,
transmitting it to the server, and calling the appropriate method is all automatic and invisible to
you. The result is a clear, easily written code structure that supports event-driven development.

enum (C# Reference)


• The enum keyword is used to declare an enumeration, a distinct type consisting of a
set of named constants called the enumerator list.
• Every enumeration type has an underlying type, which can be any integral type
except char.
• The default underlying type of the enumeration elements is int.
• By default, the first enumerator has the value 0, and the value of each successive
enumerator is increased by 1. For example:
• enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
• In this enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth.
• Enumerators can have initializers to override the default values. For example:
• enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
• In this enumeration, the sequence of elements is forced to start from 1 instead of 0.
• The default value of an enum E is the value produced by the expression (E)0.
• An enumerator may not contain white space in its name.
• However, an explicit cast is needed to convert from enum type to an integral type.
For example, the following statement assigns the enumerator Sun to a variable of the
type int using a cast to convert from enum to int:
int x = (int)Days.Sun;

Example
In this example, an enumeration, Days, is declared. Two enumerators are explicitly converted to
integer and assigned to integer variables.
// keyword_enum.cs
// enum initialization:
using System;
public class EnumTest
{
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

static void Main()


{
int x = (int)Days.Sun;
int y = (int)Days.Fri;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Fri = {0}", y);
}
}
Output
Sun = 2
Fri = 7

// keyword_enum2.cs
// Using long enumerators
using System;
public class EnumTest
{
enum Range :long {Max = 2147483648L, Min = 255L};
static void Main()
{
long x = (long)Range.Max;
long y = (long)Range.Min;
Console.WriteLine("Max = {0}", x);
Console.WriteLine("Min = {0}", y);
}
}
Output
Max = 2147483648
Min = 255

Configuration Management in ASP.NET 2.0 - Part 1


One new, important feature in ASP.NET 2.0 is the ability to read/edit the configuration files in
local machine or remote machine.
In ASP.NET 1.x, editing of the configuration files was not supported. Only option to edit a
configuration file is to treat the configuration file as an xml file and update that xml file. The major
drawback in this method is that you need to treat all the sections in the configuration file as XML
Node, which is not strongly typed. Hence, you can do only string manipulation to update any
configuration settings in that file.
However, in ASP.NET 2.0 you have strongly typed API’s to read/edit the configuration files.
The various options available to read/edit the configuration files are
Using Web Site Administration Tool
Using ASP.NET Microsoft Management Console(MMC)
Using Configuration API’s

Using Web Site Administration Tool


Web site Administration tool is a simple web interface for managing web site configuration. This
tool can be invoked using following two options
By selecting ASP.NET Configuration from Website menu option in VS.NET ( Website 
ASP.NET Configuration)
By accessing webadmin.axd file from root directory of any webapplication. For example,
http://localhost/webapplication1/webadmin.axd

Configuration settings for web site administration tool are stored in machine.config file in
<WebsiteAdministrationTool> section. Sample configuration of websiteadministration tool is show
below
<webSiteAdministrationTool
defaultUrl=”/aspnet_webadmin/2_0_40607/default.aspx”
physicalPath=”<anystring>”
enabled=”[true|false]”
localOnly=”[true|false]”
>
<categories>
<category navigateUrl="default.aspx" title="Home" />
<category navigateUrl="security/security.aspx" title="Security" />
….
</categories>
Httphandler (webadmin.axd) and VS.NET will pick the default URL setting from this section to
open the web site administration tool.
If you want to allow users to access administration site from remote machine, then you can set
localOnly attribute to true.
Similarly, if you want to restrict certain users from accessing administration site in your web
server, then you can use authorization section to mention that.
Finally, categories section is used to mention about categories tab in administration tool. By
default, this tool has four tabs - security, profile, application and provider. If you want to add new
tab to this tool, then you need to register about that tab in this section.
This tool can be used not only for editing web.config file, but also for managing web site. For
example, you can use this tool to create users and roles for a website and for managing profile
values. When you use this tool for this first time and if the configuration file does not exist for that
web application, then this tool will create a web.config with default settings for that application.
Along with web.config file, this tool also creates default site database, which is Access database
(AspNetDB.mdb) in data folder of that web application. This tool uses this database to store data
like users and roles. If the default provider is mentioned for this web application, then this tool will
use that database. It will not create a new database for its use.
As mentioned early, this tool has four tabs security, profile, application and provider.
Application tab is used to manage
1. Appsettings section in config file. You can add/modify appsetting name value pairs
2. SMPT settings
3. Debugging and Tracing section in config file.
4. Counter and site statistics tracking section in config file.
Security tab is used to manage
1. Authentication and Authorization settings in config file.
2. For creating user and roles when authentication is forms authentication. You can also map
users to roles in this section.
Provider tab is used to manage providers for that website. You can use this tab to create new
provider or for modifying existing provider settings.
Profile tab is used to manage how the web site collects personal information. You can use this tab
to enable profile tracking for a website; you can also create new profile for a website. You can use
this tab to clean up the profile values for a web site. You can view the various reports of profile
data from this tab.

AutoPostBack is built into the form-based server controls, and when enabled, automatically
posts the page back to the server whenever the value of the control in question is changed.

Autopost back is an event when a button clicks (most of the controls will have this event). If a
control property is set to autopostback = true, then the page will be relod. That is Page_load()
funtion will be excuted. if u don't want to execute the page_Load() function u have mention
if(!Page.IsnotPostBack) condition.

ASP.NET rich data controls:


ASP.NET includes some rich data controls that support repeated-value binding. The rich data
controls are designed exclusively for data binding. They also have the ability to display several
properties or fields from each data item, often in a table-based layout or according to a template
youve defined; they support higher-level features such as editing; and they provide several
events that allow you to plug into the controls inner workings at various points.
The rich data controls include the following:
GridView: The GridView is an all-purpose grid control for showing large tables of information. It
supports selecting, editing, sorting, and paging. The GridView is the heavyweight of ASP.NET
data controls. Its also the successor to the ASP.NET 1.x DataGrid.
DetailsView: The DetailsView is ideal for showing a single record at a time, in a table that has
one row per field. The DetailsView supports editing and optional paging controls that allow you to
browse through a sequence of records.
FormView: Like the DetailsView, the FormView shows a single record at a time, supports editing,
and provides paging controls for moving through a series of records. The difference is that the
FormView is based on templates, which allow you to combine fields in a much more flexible
layout that doesnt need to be based on a table.
Differences between Datagrid, Datalist and Repeater?
Datagrid
It advanced features and lets you do lot many things like paging and sorting your data without
much effort.
It can hold text data, but not linked or embedded objects.
Default look is a grid (customizable table) ·
Can customize look of table extensively. ·
Options for auto-formatting. ·
Can specify output using bound columns, columns of buttons or hyperlinks, and custom
columns created using templates. ·
No separator template. However, the grid renders in a table, and you can specify table border
size and color. ·
WYSIWYG template editing ·
Items support styles for custom look. ·
Editable contents, including deletion ·
Single and multiple selection ·
Optional paged output ·Support for sorting ·
Support for custom functionality that can be applied to items

Repeater
It does not have the paging feature but we can do it by coding.
It which can hold other controls and can embed objects.
It can embed a Datagrid within it but not viceversa.
It is used in places where you need more control over the rendering of your data
It have very flexible templates that give you total control over the formatting of your data
Read-only; no inherent support for selection or editing ·
No inherent look; you lay out the list by creating templates.
List can be vertical, horizontal, all on one line, or in any format you specify. ·
No default paging; all data is displayed in a single list. ·
Separators between elements can be defined using a template
A repeater is used when more intimate control over html generation is required.

Datalist
Datalist doesn’t has paging support
Datalist has a property called repeat. Direction = vertical/horizontal. (This is of great help in
designing layouts). This is not there in Datagrid.
The Repeater repeats a chunk of HTML you write, it has the least functionality of the three.
DataList is the next step up from a Repeater; accept you have very little control over the HTML
that the control renders.
DataList is the first of the three controls that allow you Repeat-Columns horizontally or vertically.
Finally, the DataGrid is the motherload. However, instead of working on a row-by-row basis,
you’re working on a column-by-column basis. DataGrid caters to sorting and has basic paging for
your disposal. Again you have little control, over the HTML. NOTE: DataList and DataGrid both
render as HTML tables by default.
The DataGrid displays a table in the standard row/column format while the DataList displays the
data source as a list of records. We can edit data in both but in case of datarepeater we can just
display data just like in data list but we can not edit that.

Difference Between Custom control & User Control


Custom Control
1. You create a Custom control when it is going to be used across different applications
2. Custom controls don't have a visual interface.
3. Custom controls however can be added to your tool box and used in different applications
without re-compiling. if you want to use user control in multiple application then separate copy of
user control needs to be added to each application for use.
4. It's a .dll file
5. It doesn't support caching
6. It is a pre-compiled code
7. It is global to all the application
8. To use it simply add it to GAC.

User Control
1. If the control you are going to create is only for a particular website then User Control is the
best option
2. User controls have a visual interface
3. User control will not appear in tool box and it will not have design support and loaded at
runtime.
4. It's an .ascx file.
5. it supports caching
6. It is not a pre-compiled code
7. It is Local to a particular application.
8. To use it u'll have to place the user control in each of the pages you want to use the user
control in.

Difference between ExecuteNonQuery and ExecuteScalar & ExecuteReader


ExecuteNonQuery method
- is used for Sending SQL Insert, Update & Delete statements to a database. After Executing Sql
stmt Returns no of rows Effected. It is used for execution of DML commands.
- is used to perform Catalog operation like Creating table in database or Changing of data in
tables (with out using Dataset) by useing Insert , Update,Delete
- It will not return any rows affected by the command. But it wll return a value specifing how many
rows affected by the Command. ex : select count(*) from emp
Usage: cmd.ExecuteNonQuery

ExecuteScalar method
- is used for Retrieving a single value from a returned row.
- is used to get aggregate value.
- will return only on value that is first column value of the first row in the executed query.
- This is very light-weight and is perfect when all your query asks for is one item.
This would be excellent for receiving a count of records (Select Count(*)) in an sql statement, or
for any query where only one specific field in one column is needed.
- Usage: cmd.ExecuteScalar

ExecuteReader method
- is used for Sending SQL Select statements to a database & Invoking Stored Procedures.
- is used to get set records by specified query. see the example bellow
- basically, this method returns a DataReader which is filled with the data that is retrieved using
the command. This is known as a forward-only retrieval of records - it uses your sql statement to
read through the table from the first to the last.
- Usage: cmd.ExecuteReader

SqlConnection con = new SqlConnection(constr); // constr can be connection of string.


SqlCommand cmd = new SqlCommand("select * from emp", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while(dr.Read())
{
Console.WriteLine(dr.GetString(0));
}
dr.Close();
//Implicitly closes the connection because CommandBehavior.CloseConnection was specified.

By now, most of us know what autoresponders are. What they basically do is reply to an
email/request for information with a pre-written response. For example, many websites
have setup an autoresponder that when queried (usually by receiving a blank email
message from someone wanting information), sends back a prewritten response listing
product prices.

Validation Controls

RequiredFieldValidator
RangeValidator
RegularExpressionValidator
CompareValidator
CustomValidator
ValidationSummary

RequiredFieldValidator
The RequiredFieldValidator control ensures that the user does not skip an entry. The
control fails validation if the value it contains does not change from its initial value when
validation is performed. If all the fields in the page are valid, the page is valid.

The following sample illustrates using the RequiredFieldValidator control.


<html>
<body>

<h3><font face="Verdana">RequiredFieldValidator
Example</font></h3>

<form runat=server>

Name: <asp:TextBox id=Text1 runat="server"/>

<asp:RequiredFieldValidator
id="RequiredFieldValidator1" ControlToValidate="Text1"
Font-Names="Arial" Font-Size="11" runat="server">
Required field!
</asp:RequiredFieldValidator>

<p>

<asp:Button id="Button1" runat="server"


Text="Validate" />

</form>
</body>
</html>

RangeValidator
The RangeValidator control tests whether an input value falls within a given range.
RangeValidator uses three key properties to perform its validation: ControlToValidate
contains the value to validate, MinimumValue defines the minimum value of the valid
range, and MaximumValue defines the maximum value of the valid range. These
constants are stored as string values, but are converted to the data type defined by Type
when the comparison is performed.

The following sample illustrates the RangeValidator control.

<%@ Page clienttarget=downlevel %>

<html>
<head>
<script language="C#" runat="server">

void Button1_Click(Object sender, EventArgs e) {


rangeValInteger.Validate();
if (rangeValInteger.IsValid) {
lblOutput1.Text = "Result: Valid!";
} else {
lblOutput1.Text = "Result: Not Valid!";
}

rangeValDate.Validate();
if (rangeValDate.IsValid) {
lblOutput2.Text = "Result: Valid!";
} else {
lblOutput2.Text = "Result: Not Valid!";
}

rangeValString.Validate();
if (rangeValString.IsValid) {
lblOutput3.Text = "Result: Valid!";
} else {
lblOutput3.Text = "Result: Not Valid!";
}

if (Page.IsValid) {
lblOutput.Text = "Result: Page Valid!";
} else {
lblOutput.Text = "Result: Page Not valid!";
}
}

</script>

</head>
<body>

<h3><font face="Verdana">RangeValidator Sample</font></h3>


<p>

<form runat="server">

<table bgcolor="#eeeeee" cellpadding=10>


<tr valign="top">
<td>
<h5><font face="Verdana">Value to Check:</font></h5>
<asp:TextBox Selected id="txtComp1" runat="server"/>
</td>
<td>
<h5><font face="Verdana">Data Type: Integer Min(1),
Max(10)</font></h5>
</td>
<td>
<asp:Label id="lblOutput1" Font-Names="verdana" Font-
Size="10pt" runat="server" />
</td>
</tr>
<tr valign="top">
<td>
<h5><font face="Verdana">Value to Check:</font></h5>
<asp:TextBox Selected id="txtComp2" runat="server"/>
</td>
<td>
<h5><font face="Verdana">Data Type: Date Min(2000/1/1),
Max(2001/1/1)</font></h5>
</td>
<td>
<asp:Label id="lblOutput2" Font-Names="verdana" Font-
Size="10pt" runat="server" />
</td>
</tr>
<tr valign="top">
<td>
<h5><font face="Verdana">Value to Check:</font></h5>
<asp:TextBox Selected id="txtComp3" runat="server"/>
</td>
<td>
<h5><font face="Verdana">Data Type: String Min(Aardvark),
Max(Zebra)</font></h5>
</td>
<td>
<asp:Label id="lblOutput3" Font-Names="verdana" Font-
Size="10pt" runat="server" />
</td>
</tr>
</table>

<asp:Button Text="Validate" ID="Button1" onclick="Button1_Click"


runat="server" />

<asp:RangeValidator
id="rangeValInteger"
Type="Integer"
ControlToValidate="txtComp1"
MaximumValue="10"
MinimumValue="1"
runat="server"/>

<asp:RangeValidator
id="rangeValDate"
Type="Date"
ControlToValidate="txtComp2"
MaximumValue="2001/1/1"
MinimumValue="2000/1/1"
runat="server"/>

<asp:RangeValidator
id="rangeValString"
Type="String"
ControlToValidate="txtComp3"
MaximumValue="Zebra"
MinimumValue="Aardvark"
runat="server"/>
<br>

<asp:Label id="lblOutput" Font-Names="verdana" Font-Size="10pt"


runat="server" />

</form>

</body>
</html>

RegularExpressionValidator
The RegularExpressionValidator control confirms that the entry matches a pattern
defined by a regular expression. This type of validation allows you to check for
predictable sequences of characters, such as those in social security numbers, e-mail
addresses, telephone numbers, postal codes, and so on.

RegularExpressionValidator uses two key properties to perform its validation:


ControlToValidate contains the value to validate, and ValidationExpression contains
the regular expression to match.

The following sample illustrates using the RegularExpressionValidator control.


<html>
<head>
<script language="C#" runat=server>

void ValidateBtn_Click(Object Src, EventArgs E) {

if (Page.IsValid) {
lblOutput.Text = "Page is Valid!";
}
else {
lblOutput.Text = "Page is InValid! :-(";
}
}

</script>

</head>
<body>

<h3><font face="Verdana">Simple RegularExpressionValidator


Sample</font></h3>

<form runat="server">

<table bgcolor="#eeeeee" cellpadding=10>

<tr valign="top">
<td colspan=3>
<asp:Label ID="lblOutput" Text="Enter a 5 digit zip code"
Font-Names="Verdana" Font-Size="10pt" runat="server"/>
</td>
</tr>

<tr>
<td colspan=3>
<font face=Verdana size=2><b>Personal Information</b></font>
</td>
</tr>

<tr>
<td align=right>
<font face=Verdana size=2>Zip Code:</font>
</td>
<td>
<ASP:TextBox id=TextBox1 runat=server />
</td>
<td>
<asp:RegularExpressionValidator
id="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationExpression="\d{5}"
Display="Static"
Font-Names="verdana"
Font-Size="10pt">
Zip code must be 5 numeric digits
</asp:RegularExpressionValidator>
</td>
</tr>

<tr>
<td></td>
<td>
<ASP:Button text="Validate" OnClick="ValidateBtn_Click"
runat=server />
</td>
<td></td>
</tr>
</table>

</form>

</body>
</html>

CompareValidator
The CompareValidator control compares the value of one control to another, or to an
explicit value in the control's ValueToCompare property.

Note: For the purpose of validation, a specific property on the control is designated as its
"value". For more information, see the Validating Form Inputs section.

CompareValidator uses three key properties to perform its validation.


ControlToValidate and ControlToCompare contain the values to compare. Operator
defines the type of comparison to perform, for example, Equal or Not Equal.
CompareValidator performs the validation by evaluating these properties as an
expression, as shown in the following example.

<ControlToValidate> <Operator> <ControlToCompare>

If the expression evaluates true, the validation result is valid.

The following sample illustrates using the CompareValidator control.

<%@ Page clienttarget=downlevel %>

<html>
<head>
<script language="C#" runat="server">

void Button1_OnSubmit(Object sender, EventArgs e) {

if (Page.IsValid) {
lblOutput.Text = "Result: Valid!";
}
else {
lblOutput.Text = "Result: Not valid!";
}
}

void lstOperator_SelectedIndexChanged(Object sender, EventArgs


e) {

comp1.Operator = (ValidationCompareOperator)
lstOperator.SelectedIndex;
comp1.Validate();
}

</script>
</head>
<body>

<h3><font face="Verdana">CompareValidator Example</font></h3>


<p>Type a value in each textbox, select a comparison operator, then
click "Validate" to test.</p>

<form runat=server>

<table bgcolor="#eeeeee" cellpadding=10>


<tr valign="top">
<td>
<h5><font face="Verdana">String 1:</font></h5>
<asp:TextBox Selected="True" id="txtComp"
runat="server"></asp:TextBox>
</td>
<td>
<h5><font face="Verdana">Comparison Operator:</font></h5>

<asp:ListBox id="lstOperator"
OnSelectedIndexChanged="lstOperator_SelectedIndexChanged"
runat="server">
<asp:ListItem Selected="True" Value="Equal"
>Equal</asp:ListItem>
<asp:ListItem Value="NotEqual"
>NotEqual</asp:ListItem>
<asp:ListItem Value="GreaterThan"
>GreaterThan</asp:ListItem>
<asp:ListItem Value="GreaterThanEqual"
>GreaterThanEqual</asp:ListItem>
<asp:ListItem Value="LessThan"
>LessThan</asp:ListItem>
<asp:ListItem Value="LessThanEqual"
>LessThanEqual</asp:ListItem>
</asp:ListBox>
</td>
<td>
<h5><font face="Verdana">String 2:</font></h5>
<asp:TextBox id="txtCompTo" runat="server"></asp:TextBox><p>
<asp:Button runat=server Text="Validate" ID="Button1"
onclick="Button1_OnSubmit" />
</td>
</tr>
</table>

<asp:CompareValidator id="comp1" ControlToValidate="txtComp"


ControlToCompare = "txtCompTo" Type="String" runat="server"/>

<br>

<asp:Label ID="lblOutput" Font-Names="verdana" Font-Size="10pt"


runat="server"/>

</form>

</body>
</html>

CustomValidator
The CustomValidator control calls a user-defined function to perform validations that
the standard validators can't handle. The custom function can execute on the server or in
client-side script, such as JScript or VBScript. For client-side custom validation, the
name of the custom function must be identified in the ClientValidationFunction
property. The custom function must have the form function myvalidator(source,
arguments) Note that source is the client-side CustomValidator object, and arguments
is an object with two properties, Value and IsValid. The Value property is the value to be
validated and the IsValid property is a Boolean used to set the return result of the
validation. You can view a client-side validation example in the Validating Form Input
Controls section.

For server-side custom validation, place your custom validation in the validator's
OnServerValidate delegate.

The following sample illustrates using the CustomValidator control.

<html>
<head>
<script language="C#" runat=server>

void ValidateBtn_OnClick(object sender, EventArgs e) {

if (Page.IsValid) {
lblOutput.Text = "Page is valid!";
}
else {
lblOutput.Text = "Page is not valid! :-(";
}
}

void ServerValidate (object source, ServerValidateEventArgs value) {


int num;
// even number?
if (int.TryParse(value.Value, out num) ) {
value.IsValid = (num % 2 == 0);
}
else {
value.IsValid = false;
}
}

</script>

</head>
<body>

<h3><font face="Verdana">CustomValidator Example</font></h3>


<form runat="server">

<asp:Label id=lblOutput runat="server"


Text="Enter an even number:"
Font-Names="Verdana"
Font-Size="10pt" /><br>

<p>

<asp:TextBox id=Text1 runat="server" />

&nbsp;&nbsp;

<asp:CustomValidator id="CustomValidator1" runat="server"


ControlToValidate="Text1"
OnServerValidate="ServerValidate"
Display="Static"
Font-Names="verdana" Font-Size="10pt">
Not an even number!
</asp:CustomValidator>

<p>

<asp:Button text="Validate" onclick="ValidateBtn_OnClick"


runat="server" />

</form>

</body>
</html>

ValidationSummary
When the user's input is processed (for example, when the form is submitted), the Web
Forms framework passes the user's entry to the associated validation control or controls.
The validation controls test the user's input and set a property to indicate whether the
entry passed the validation test. After all validation controls have been processed, the
IsValid property on the page is set; if any of the controls shows that a validation check
failed, the entire page is set to invalid.

A ValidationSummary control is displayed when the IsValid property of the page is


false. It "polls" each of the validation controls on the page and aggregates the text
messages exposed by each. The following sample illustrates displaying errors with a
ValidationSummary.

<%@ Page clienttarget=downlevel %>

<html>
<head>
<script language="C#" runat=server>

void ListFormat_SelectedIndexChanged(Object Sender, EventArgs E


) {
// Change display mode of the validator summary when a new
option
// is selected from the "ListFormat" dropdownlist

valSum.DisplayMode = (ValidationSummaryDisplayMode)
ListFormat.SelectedIndex;
}

</script>

</head>
<body>

<h3><font face="Verdana">ValidationSummary Sample</font></h3>


<p>

<form runat="server">

<table cellpadding=10>
<tr>
<td>
<table bgcolor="#eeeeee" cellpadding=10>

<tr>
<td colspan=3>
<font face=Verdana size=2><b>Credit Card
Information</b></font>
</td>
</tr>
<tr>
<td align=right>
<font face=Verdana size=2>Card Type:</font>
</td>
<td>
<ASP:RadioButtonList id=RadioButtonList1
RepeatLayout="Flow" runat=server>
<asp:ListItem>MasterCard</asp:ListItem>
<asp:ListItem>Visa</asp:ListItem>
</ASP:RadioButtonList>
</td>
<td align=middle rowspan=1>
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
ControlToValidate="RadioButtonList1"
ErrorMessage="Card Type. "
Display="Static"
InitialValue="" Width="100%" runat=server>
*
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align=right>
<font face=Verdana size=2>Card Number:</font>
</td>
<td>
<ASP:TextBox id=TextBox1 runat=server />
</td>
<td>
<asp:RequiredFieldValidator id="RequiredFieldValidator2"
ControlToValidate="TextBox1"
ErrorMessage="Card Number. "
Display="Static"
Width="100%" runat=server>
*
</asp:RequiredFieldValidator>

</td>
</tr>
<tr>
<td align=right>
<font face=Verdana size=2>Expiration Date:</font>
</td>
<td>
<ASP:DropDownList id=DropDownList1 runat=server>
<asp:ListItem></asp:ListItem>
<asp:ListItem >06/00</asp:ListItem>
<asp:ListItem >07/00</asp:ListItem>
<asp:ListItem >08/00</asp:ListItem>
<asp:ListItem >09/00</asp:ListItem>
<asp:ListItem >10/00</asp:ListItem>
<asp:ListItem >11/00</asp:ListItem>
<asp:ListItem >01/01</asp:ListItem>
<asp:ListItem >02/01</asp:ListItem>
<asp:ListItem >03/01</asp:ListItem>
<asp:ListItem >04/01</asp:ListItem>
<asp:ListItem >05/01</asp:ListItem>
<asp:ListItem >06/01</asp:ListItem>
<asp:ListItem >07/01</asp:ListItem>
<asp:ListItem >08/01</asp:ListItem>
<asp:ListItem >09/01</asp:ListItem>
<asp:ListItem >10/01</asp:ListItem>
<asp:ListItem >11/01</asp:ListItem>
<asp:ListItem >12/01</asp:ListItem>
</ASP:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator id="RequiredFieldValidator3"
ControlToValidate="DropDownList1"
ErrorMessage="Expiration Date. "
Display="Static"
InitialValue=""
Width="100%"
runat=server>
*
</asp:RequiredFieldValidator>
</td>
<td>
</tr>
<tr>
<td></td>
<td>
<ASP:Button id=Button1 text="Validate" runat=server />
</td>
<td></td>
</tr>
</table>
</td>
<td valign=top>
<table cellpadding=20><tr><td>
<asp:ValidationSummary ID="valSum" runat="server"
HeaderText="You must enter a value in the following
fields:"
Font-Names="verdana"
Font-Size="12"
/>
</td></tr></table>
</td>
</tr>
</table>

<font face="verdana" size="-1">Select the type of validation summary


display you wish: </font>

<asp:DropDownList id="ListFormat" AutoPostBack=true


OnSelectedIndexChanged="ListFormat_SelectedIndexChanged" runat=server >
<asp:ListItem>List</asp:ListItem>
<asp:ListItem selected>Bulleted List</asp:ListItem>
<asp:ListItem>Single Paragraph</asp:ListItem>
</asp:DropDownList>

</form>

</body>
</html>