You are on page 1of 68

Ajax Tab Container Extender in ASP.

Net
The TabContainer is an AJAX Control to create a set of Tabs to organize the contents of an
ASP.Net page. It is uesd to host a number of TabPanels in which we use a Text Header or
HeaderTemplate as well as a ContentTemplate that defines its content.

Now we will see an example of an Ajax Tab Container extender in ASP.NET.


Step 1
First we will create a new project that is an ASP.NET WebApplication named
AjaxTabContainer.

Now add one WebForm to this project named TabContainer.aspx.

Step 2
We will now open the Toolbox then select the Ajax Pane and drag ToolkitScriptManager to
the div tag inside the WebForm.

Step 3
We will now select a TabContainer control from the ajax controls pane and add it after the
ToolKitScriptManager.

Step 4
Now open the properties of the Tabcontainer and click the Add Tab Panels option.
It will create a new Tab Panels in our TabContainer control, here we will create two Tab
Panels.

Now the source code will look like this.

For using Ajax Controls first we need to add an AjaxControlToolkit reference to our
application.
1.

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix


="asp" %>

We can use a TagPrefix also, for example:


tagPrefix="ajax", tagPrefix="cc1",tagPrefix="asp"
Step 5
Now we will change the HeaderText in the TabPanels using the following code.
1.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TabContainer.aspx.cs"


Inherits="AjaxTabContainer.TabContainer" %>

2.
3.

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix


="asp" %>

4.
5.

<!DOCTYPE html>

6.
7.

<html xmlns="http://www.w3.org/1999/xhtml">

8.

<head runat="server">

9.

<title></title>

10. </head>

11. <body>
12.

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

13.

<div>

14.
15.

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">

16.

</asp:ToolkitScriptManager>

17.

<br />

18.

<asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="1" Height="


40px" Width="241px">

19.

<asp:TabPanel runat="server" HeaderText="Login Form" ID="TabPanel1">

20.

</asp:TabPanel>

21.

<asp:TabPanel ID="TabPanel2" runat="server" HeaderText="Registration Form">

22.

</asp:TabPanel>

23.

</asp:TabContainer>

24.
25.

</div>

26.

</form>

27. </body>
28. </html>

It will look like this in the design view.

Now run the application and see the output.

Step 6
Now we want to design something in these Tab Panels. We will select the Tab Panel in
source view then we will write <contentTamplate> </contentTamplate> tag.
Here for example we will design the Login page in the first panel using the following
code.
1.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TabContainer.aspx.cs"


Inherits="AjaxTabContainer.TabContainer" %>

2.
3.

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix


="asp" %>

4.
5.

<!DOCTYPE html>

6.
7.

<html xmlns="http://www.w3.org/1999/xhtml">

8.

<head runat="server">

9.

<title></title>

10. </head>
11. <body>
12.

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

13.

<div>

14.
15.

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">

16.

</asp:ToolkitScriptManager>

17.

<br />

18.

19.
20.
21.

22.
23.

<asp:TabContainer ID="TabContainer1" runat="server"


="165px" Width="350px">

ActiveTabIndex="0" Height

<asp:TabPanel runat="server" HeaderText="Login Form" ID="TabPanel1">


<ContentTemplate>
<asp:Label ID="lbllogin" runat="server" Text="Login Here" "True" "True" "True
" ForeColor="#660033"></asp:Label>
<table style="width: 100%;" border:"1">
<tr>

24.

<td><asp:Label ID="lbluname" runat="server" Text="UserName" "True"


ForeColor="#000099"></asp:Label>
</td>

25.

<td><asp:TextBox ID="tbuname" runat="server"></asp:TextBox></td>

26.

</tr>

27.

<tr>

28.

29.

<td><asp:Label ID="lblpass" runat="server" Text="Password" "True" For


eColor="#000099"></asp:Label>
</td>
<td><asp:TextBox ID="tbpass" runat="server"></asp:TextBox></td>

30.

</tr>

31.

<tr>

32.
33.

34.
35.
36.

<td> </td>
<td><asp:Button ID="btnSubmit" runat="server" Text="Submit" BackCol
or="#00CCFF" ForeColor="Blue" /></td>
</tr>
</table>
</ContentTemplate>

37.

</asp:TabPanel>

38.

<asp:TabPanel ID="TabPanel2" runat="server" HeaderText="Registration Form">

39.

</asp:TabPanel>

40.

</asp:TabContainer>

41.
42.

</div>

43.

</form>

44. </body>
45. </html>

Now it looks like this in design view.

Now we will run the project and see the output for the Login form panel.

Step 7: Now for the second panel we will design the Registration page with the following
code.
The following is the complete code for the Login and Registration Forms.
1.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TabContainer.aspx.cs"


Inherits="AjaxTabContainer.TabContainer" %>

2.
3.

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix


="asp" %>

4.
5.

<!DOCTYPE html>

6.
7.

<html xmlns="http://www.w3.org/1999/xhtml">

8.

<head runat="server">

9.

<title></title>

10. </head>
11. <body>
12.

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

13.

<div>

14.
15.

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">

16.

</asp:ToolkitScriptManager>

17.

<br />

18.

<asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="1" Height="


229px" Width="353px">

19.

<asp:TabPanel runat="server" HeaderText="Login Form" ID="TabPanel1">

20.
21.

22.
23.
24.

<ContentTemplate>
<asp:Label ID="lbllogin" runat="server" Text="Login Here" "True" "True" "True
" ForeColor="#660033"></asp:Label>
<table style="width: 100%;" border:"1">
<tr>
<td><asp:Label ID="lbluname" runat="server" Text="UserName" "True"
ForeColor="#000099"></asp:Label></td>

25.

<td><asp:TextBox ID="tbuname" runat="server"></asp:TextBox></td>

26.

</tr>

27.

<tr>

28.

<td><asp:Label ID="lblpass" runat="server" Text="Password" "True" For


eColor="#000099"></asp:Label></td>

29.

<td><asp:TextBox ID="tbpass" runat="server"></asp:TextBox></td>

30.

</tr>

31.

<tr>

32.
33.

<td> </td>
<td><asp:Button ID="btnSubmit" runat="server" Text="Submit" BackCol
or="#0099FF" "True" ForeColor="#000099" Height="27px" /></td>

34.

</tr>

35.

</table>

36.

</ContentTemplate>

37.

</asp:TabPanel>

38.

<asp:TabPanel ID="TabPanel2" runat="server" HeaderText="Registration Form">

39.
40.

<ContentTemplate>
<asp:Label ID="lblRegistration" runat="server" Text="Registration Here" "True
" "True" "True" ForeColor="#660033"></asp:Label>

41.

<table style="width: 100%;" border:"1">

42.
43.

<tr>
<td><asp:Label ID="lblUserName" runat="server" Text="UserName" "Tr
ue" ForeColor="#000099"></asp:Label></td>

44.

<td><asp:TextBox ID="tbUserName" runat="server"></asp:TextBox></t


d>

45.

</tr>

46.

<tr>

47.

<td><asp:Label ID="lblPassword" runat="server" Text="Password" "True


" ForeColor="#000099"></asp:Label></td>

48.

<td><asp:TextBox ID="tbPassword" runat="server"></asp:TextBox></t


d>

49.

</tr>

50.
51.

<tr>
<td><asp:Label ID="lblFname" runat="server" Text="FirstName" "True"
ForeColor="#000099"></asp:Label></td>

52.

<td><asp:TextBox ID="tbFname" runat="server"></asp:TextBox></td>

53.

</tr>

54.

<tr>

55.

<td><asp:Label ID="lblLastName" runat="server" Text="LastName" "Tru


e" ForeColor="#000099"></asp:Label></td>

56.

<td><asp:TextBox ID="tbLastName" runat="server"></asp:TextBox></t


d>

57.

</tr>

58.

<tr>

59.
60.

<td> </td>
<td><asp:Button ID="btnsave" runat="server" Text="Save" BackColor="
#0099FF" "True" ForeColor="#000099" Height="27px"/></td>

61.

</tr>

62.

</table>

63.

</ContentTemplate>

64.

</asp:TabPanel>

65.

</asp:TabContainer>

66.

</div>

67.

</form>

68. </body>
69. </html>

Now it is look like this in design view.

Now we will run the project and see the output for the Registration form panel.

Step 8: Now we will set some properties like AutoPostBack and BorderColor for the Tab
Container.
The AutoPostBack is used when a tab is changed after a postback, we will get the same
tab after postback.

It is all about how to use an Ajax Tab Container extender in ASP.NET.

Introduction to Ajax and Ajax Control


Toolkit
Introduction
In traditional web sites there are many issues related to performance of an application
due to the high traffic on the server because when the user wants just a particular part of

information then at that time the entire web page or web site is reloaded but that is not
necessary.
Problems in traditional web Applications
1. Many round trips to the server.
2. Rendering of webpage is slower.
3. Increases the consumption of server resources.
4. Response time of application is very slower.
5. Rendering of data is static.
6. Data is updated of an application only when the user clicks on the browser refresh
button.
So the preceding is some of the basic problems related to the traditional web application
so to overcome these problems Ajax is the best alternative. So let us start with the
basics.
What is Ajax ?
Ajax stands for Asynchronous JavaScript and XML; in other words Ajax is the combination
of various technologies such as a JavaScript, CSS, XHTML, and DOM etc.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of
data with the server behind the scenes. This means that it is possible to update parts of a
web page, without reloading the entire page.
We can also define Ajax is a combination of client side technologies that provides
asynchronous communication between the user interface and the web server so that
partial page rendering occurs instead of complete page post back.
Ajax is platform-independent; in other words AJAX is a cross-platform technology that can
be used on any Operating System since it is based on XML & JavaScript. It also supports
open source implementation of other technology. It partially renders the page to the
server instead of complete page post back. We use AJAX for developing faster better and
more interactive web applications. AJAX uses a HTTP request between web server &
browser.
Using Ajax technologies we can observe in Google Maps, Gmail, YouTube, and Facebook
tabs.

I hope you have understood the basic concepts of Ajax. Now let us see the following
diagram showing how Ajax works:

In the above diagram it's clear how Ajax works, that first depending on the client
requests the browser creates theXMLHttpRequest and sends it to the server and there
after that the server processes the HttpRequest given by the browser, processes it and
then sends the response back to the user and at the end the browser processes the
response given by the server using JavaScript and update the requested content of the
particular page instead of the entire page contents.
AJAX is Based on Internet Standards
AJAX is based on internet standards, and uses a combination of a XMLHttpRequest object
to exchange data asynchronously with a server, JavaScript and DOM to interact with the
information and CSS is used to style the data and XML is often used as the format for
transferring data.
Let us know about the basic information each technology uses in Ajax.
1. XHTML and CSS
XHTML (or HTML) is used for providing the markup tags, as used in any typical web site.
In addition, we utilize CSS for extra styling functionality in relation to presentation and
layout. XHTML is a stricter and more standardized form of HTML, which follows the rules
of XML such as the requirement for well-formatted and valid against a schema or DTD.
2. Document Object Model (DOM)

The Document Object Model is a platform and language independent standard object
model for representing HTML or XML.
3. XML
XML is typically used as the format for transferring data between the server and the
client. Using XML we can represent any applicable data object structure we might wish to
represent.
4. XMLHttpRequest (XHR) and JavaScript
The XMLHttpRequest is the core of the Ajax model; without it the model would not exist.
The XMLHttpRequest JavaScript object is the enabling technology which is used to
exchange data asynchronously with the web server. In short, XMLHttpRequest lets us use
JavaScript to make a request to the server and process the response without blocking the
user. Naturally, as we are using this JavaScript object, the providing technology is
JavaScript and hence some knowledge of JavaScript is required to get Ajax applications to
function.
Note:

In Ajax Client and Server Communication done with help of HttpRequest.


AJAX applications are browser and platform independent.

I hope you have understood the basics concepts of Ajax. Now let us discus the relation
between Ajax and ASP.Net Framework.
Ajax and ASP.Net Framework
ASP.NET AJAX integrates client script libraries with the ASP.NET 2.0 development
framework. This new Web development technology extends ASP.NET, offering the
interactive user interface benefits of AJAX with a programming model that is more
familiar to ASP.NET developers, making it very easy to add AJAX to your applications
quickly and with minimal effort.
Power of Ajax

With AJAX, when a user clicks a button, you can use JavaScript and DHTML to
immediately update the UI, and spawn an asynchronous request to the server to
fetch results.

When the response is generated, you can then use JavaScript and CSS to update
your UI accordingly without refreshing the entire page. While this is happening,
the form on the users screen doesn't flash, blink, disappear, or stall.

The power of AJAX lies in its ability to communicate with the server
asynchronously, using a XMLHttpRequest object without requiring a browser
refresh.

Ajax essentially puts JavaScript technology and the XMLHttpRequest object


between your Web form and the server.

Everything happens behind the scenes with a minimum request and response cycle
without the knowledge of the user.
Advantages of AJAX based application

Improved application performance by reducing the amount of data downloaded


from the server

Rich, responsive and Slick UI with no page flickers

Eliminates frequent page refresh which usually happens in a typical


request/response model (Everything is updated on fly)

Easy to implement as there are variety of AJAX implementations available around

AJAX mechanism works behind the scene nothing much required from user
perspective

Works with all browsers

Avoids the round trips to the server

Rendering of webpage faster

Decreases the consumption of server resources

Response time of application is very faster

Rendering of data is dynamic

So let us start with the basic concepts of Ajax Extension which comes with the ASP.Net
Framework.
Using Ajax Extension
The following are the most commonly used Ajax controls in an ASP.Net Application which
comes with the ASP.Net Framework and available under the Ajax Extension tab of ASP.Net
Toolbox present at the left hand side of Microsoft Visual Studio framework.
These controls are:
1. ScriptManager
2. UpDatePanel
3. Timer
4. UpdateProgress
5. ScriptManagerProxy
6. Pointer

1. Using ScriptManager
When we use any Ajax control then there is a requirement to use the
ScriptManager to handle the Scripting on the client side; without the
ScriptManager Ajax controls are not run. So it's a requirement to use the
ScriptManager.

2. Using UpDatePanel
Update panel is one of the most commonly used Ajax controls which is responsible
for updating the particular requested content of the page instead of the entire
page which is not requested. The ASP.Net controls are put under the update panel
to make the benefit of this control. The ASP.Net controls which are kept under the
update panel will be updated when the user clicks on a particular ASP.Net Control
which are used in an application.
You can use multiple update panels on a single web page.

3. Using Timer
The Timer is also one of the important controls; by using it we can update the
particular content of the page automatically without clicking the browser refresh
button. The Timer control is used along with the Update Panel so the Contents put
under the update panel are automatically updated according the timing set under
the timer_click event.

4. Using Update Progress


This control is used to notify the user to wait until the requests are processed on
the server. Update progress control is used when the user clicks on any tab or
control of an application. At that time the progress bar is shown which is the
interval between the times taken by the server to process the client request.

5. Using ScriptManagerProxy
When you need to reference a service from your content page and yet the
ScriptManager resides on the Master Page use a ScriptManagerProxy. The
ScriptManagerProxy works by detecting the main ScriptManager on your page at
runtime and hooking itself to that ScriptManager, making sure that any references
given to it are also given to the real ScriptManager.

6. Using Pointer
This Ajax Control used to specify the style of the mouse pointer such as arrow,
thumb, and progress bar and much more. The above is the basic introduction
about the Ajax Extension controls which are available by default in a Microsoft
Visual Studio Framework.

Auto Refresh Data on Page Using AJAX

In this article, I explain how to auto-refresh data on an ASP.NET page after


a certain interval using AJAX UpdatePanel and other controls. I am using
some AJAX controls and using a SQL Server database and a Data Grid
control. The Database name is Northwind. In this application my interval
time for refresh data is 30 seconds. You can change your time by the
times interval property.
Here is a snapshot:

This code is for binding data:


public void BindData()
{
con = new SqlConnection("Initial Catalog=Northwind; Data Source=localhost;
Uid=sa; pwd=;");
cmd.CommandText = "select * from Employees ";
cmd.Connection = con;
con.Open();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
cmd.ExecuteNonQuery();
GridData.DataSource = ds;
GridData.DataBind();
}
You can check your current time on page load. Write this code:
MyLabel.Text = System.DateTime.Now.ToString();
BindData();
And the grid refresh time is:
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = "Grid Refreshed at: " + DateTime.Now.ToLongTimeString();
}
Here is the HTML design code:
<form id="form1" runat="server">
<asp:Label ID="Label2" runat="server" Text="This is Time, When The Full Page
Load :" Font-Bold="true"></asp:Label>&nbsp;

<asp:Label ID="MyLabel" runat="server"></asp:Label><br /><br />


<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server" Interval="30000"
>

</asp:Timer>
</div>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label3" runat="server" Text="This is The Time when Only
Data Grid will Referesh :"Font-Bold="true"></asp:Label>&nbsp;
<asp:Label ID="Label1" runat="server" Text="Grid not refreshed
yet."></asp:Label><br />
<asp:Label ID="Label4" runat="server" Text="(Grid Will Referesh after Every
30 Sec)" Font-Bold="true"></asp:Label>&nbsp;
<br /><br />
<asp:DataGrid ID=GridData runat="server" Width="100%" GridLines="Both"
HeaderStyle-BackColor="#999999" AutoGenerateColumns="false">
<Columns>
<asp:BoundColumn DataField="EmployeeID" HeaderText="Employee
ID"></asp:BoundColumn>
<asp:BoundColumn DataField="FirstName" HeaderText="First
Name"></asp:BoundColumn>
<asp:BoundColumn DataField="LastName" HeaderText="Last
Name"></asp:BoundColumn>
<asp:BoundColumn DataField="City" HeaderText="City"></asp:BoundCol
umn>
</Columns>
</asp:DataGrid>
</ContentTemplate>
</asp:UpdatePanel>
</form>

Disable Future and Past Date Of AJAX


Calendar in ASP.Net C#
Before AJAX Control Toolkit 4.0 or any other calender such as the ASP.Net Calender
Control it is a very tedious process to disable the past or future dates from a calendar.
Because to do that we need to write more than a hundred lines of code in JavaScript or
any other scripting language but we can do this by using an AJAX calendar extender with
two lines of code. So by considering the above requirement I have decided to write this
article.
So let us start with the basics.
Requirement

You need an "AJAX Control Toolkit 4.0" and above, it only works in this version

Don't forget to add the "AJAX control toolkit assembly reference" at the top of
the .aspx page source code

Don't forget to use either "Script Manager" or "ToolScript Manager" in a .aspx


page because whenever you use any AJAX control you need to use one of them to
handle scripts.

Now let us create the one sample application to do our task as:
1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
2. "File" - "New web Site" - "C#" - "Empty WebSite" (to avoid adding a master page).
3. Provide the web site a name such as AjaxCalender or another as you wish and
specify the location.
4. Then right-click on Solution Explorer - "Add New Item" - "Default.aspx" page.
5. Drag and drop one textbox and one ScriptManager from Ajax Extension section
on the <form> section of the Default aspx page.
Now the source code of the Default.aspx should look as in the following:
<formid="form1"runat="server">
<asp:ScriptManagerID="ScriptManager1"runat="server">
</asp:ScriptManager>
<div align="center">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CalendarExtenderID="Calendar1"runat="server"
Enabled="True" TargetControlID="TextBox1"Format="dd/MM/yyyy"
></asp:CalendarExtender>
</div>
</form>
Now use the following code in the .cs file.
To disable a past date use the following code in the "Page load":
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.StartDate = DateTime.Now; //to dissable past Date
}
In the above code I have set the Calendar Extender start date to the current date so I will
disable all past dates.
Now run the application; the output will look as in the following:

To disable a future date use the following code in the "Page load":
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.EndDate = DateTime.Now; //to dissable future Date
}
In the above code I have set the Calendar Extender End date to the current date so I will
disable all future dates.
Now run the application; the output will look as in the following:

Start Calendar after one month from the Present Date


protected void Page_Load(object sender, EventArgs e)
{
Calendar1.EndDate = DateTime.Now.AddMonths(1); // Start Calendar after one month
from Present Date
}

2 Ways to Implement AJAX in ASP.Net


Application
What are the ways?
My first way is to implement AJAX using Update Panel in ASP.NET and the second way is
to implement AJAX using jQuery. If you don't have a basic idea of jQuery then I suggest
you read it here then proceed with this article. Let's start with an example.

Implement AJAX using Update Panel


If you are an ASP.NET developer then you probably are aware of the AJAX Extension tab in

Visual Studio (2010 or higher generally) Toolbox and the tab has a few very useful tools
to implement AJAX in a web application. In the first example we will implement AJAX
using UpdatePanel and ScriptManager . Both tools are available in the same tab of the
Toolbox.
UpdatePanel
Let's learn a few lines about Update Panel. It's nothing but a region that will be updated
in asynchronous operations. And this is the beauty of AJAX. The contents of the
UpdatePanel will be updated and the outside content will remain the same.
ScriptManager
This is the hero of AJAX implementation in ASP.NET. Before writing any code related to
ajax ypu need to put a ScriptManager tag in the aspx page.
Let's see one example in action.
The following will print the time within an Update Panel:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
//Script manager tag is here
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
// Code outside of Update panel
Time at Load Time <%= DateTime.Now.ToLongTimeString() %>.
// code inside Update panel
<asp:UpdatePanel ID="UpdatePanel1"
runat="server" UpdateMode="Conditional">
<ContentTemplate>
Latest Time by refresh <%= DateTime.Now.ToLongTimeString() %>.
<br /><asp:Button Text="Refresh Time" ID="Button1"
runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Here is the output window:

If you try this example in your Development environment and run it then you can find the
second date display is updated after each press of the button, because it's within the
update panel. But the first label is (First Time display) as it is. OK, you are saying , "this is
a very simple example and it's not at all useful in project development". Then I will show
you something more useful than this. Let's make a little database operation by AJAX
technique.

Fetch Data from Database using AJAX


Here I would like to show how to fetch data from a database and display it within a Grid
using AJAX. The basic concept or implementation is the same. I will keep a few controls
within the Update Panel and that's all.
Here is my aspx page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DDLAjax" runat="server" Height="16px" Width="117px"
>

</asp:DropDownList>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Show"
Width="95px" />
<br />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
If you observe the content of my aspx page then you will discover that I have kept one
drop down list, one button and one GridView within the UpdatePanel. And our hero (read
ScriptManager) is just in the previous line of update panel. Now it's time to observe C#
code for the same aspx page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace YahooProject
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.DDLAjax.Items.Add("first");
this.DDLAjax.Items.Add("second");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SERVERNAME;Initial
atalog=DATABALENAME;Integrated Security=True";
con.Open();
SqlCommand cmd = null;

}
}

if (this.DDLAjax.SelectedItem.Text == "first")
{
cmd = new SqlCommand("select * from first",con);
}
if (this.DDLAjax.SelectedItem.Text == "second")
{
cmd = new SqlCommand("select * from second", con);
}
this.GridView1.DataSource = cmd.ExecuteReader();
this.GridView1.DataBind();

Hey; no rocket science here. The user will choose the table name by selecting it from the
drop down list and after clicking the button the data from the relevant table will be
fetched and bound with the Grid View. And we need to keep in mind only the component
within the update panel (here GridView basically) will be updated. Yes, after testing I
woite this article. The following is the evidence (Ha Ha..):

OK, I hope you got the basic idea of UpdatePanel to implement AJAX. Let's start with the
second approach.

Creating Modal Popup in ASP.Net


Application Using Ajax
This article explains how to create a Modal Popup in an ASP.NET application using Ajax.
In many sites you must have seen that when you click on a button a form is displayed
but it is opened on the same page and you can see the background page as well, so it
doesn't close any page yet runs on the same page on which you are working.
This is done using a Modal Popup, Ajax provides you this feature that can be used in the
ASP.NET Application.
A Modal Popup looks something like this:

Let's see the procedure to create such an application.


Step 1
First of All you need to download the "AjaxControlToolkit.dll". It can be downloaded from
the official Ajax site or you can download my application and can obtain it from the Bin
folder of my application.

Now attach this Toolkit with your ASP.NET Application, this can be done by right-clicking
on the reference and then choose to "Add Existing Item".
After attaching the Toolkit with the application you need to register this in your
application; that can be done by writing this code:
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefi
x="cc1" %>
Step 2
Now the next step is to add the Script Manager to your application so that you can use
the Tools of Ajax.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
Now we can call the ModalPopupExtender in our application as in the following:
<cc1:ModalPopupExtender ID="mp1" runat="server" PopupControlID="Panl1" TargetCon
trolID="Button1"
CancelControlID="Button2" BackgroundCssClass="Background">
</cc1:ModalPopupExtender>
In ModalPopupExtender we pass a few IDs like which ID will be used to open the Popup,
which ID will be used to close the Popu, on which ID Popup is to be open.
Step 3
Here I had used Panel as a popup and two buttons for opening and closing the
application.
Under the Panel you can create a form that is to be filled in by the End User.
Our complete code will be like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherit
s="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefi
x="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.Background
{
background-color: Black;
filter: alpha(opacity=90);
opacity: 0.8;
}
.Popup

{
background-color: #FFFFFF;
border-width: 3px;
border-style: solid;
border-color: black;
padding-top: 10px;
padding-left: 10px;
width: 400px;
height: 350px;
}
.lbl
{
font-size:16px;
font-style:italic;
font-weight:bold;
}
</style>
</head>
<body >
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Button ID="Button1" runat="server" Text="Fill Form in Popup" />
<!-- ModalPopupExtender -->
<cc1:ModalPopupExtender ID="mp1" runat="server" PopupControlID="Panl1" TargetCon
trolID="Button1"
CancelControlID="Button2" BackgroundCssClass="Background">
</cc1:ModalPopupExtender>
<asp:Panel ID="Panl1" runat="server" CssClass="Popup" align="center" style = "display
:none">
<table>
<tr>
<td>
<asp:Label runat="server" CssClass="lbl" Text="First Name"></asp:Label>
</td>
<td>
<asp:TextBox runat="server" Font-Size="14px" ></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label1" runat="server" CssClass="lbl" Text="Middle
Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server" Font-Size="14px" ></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" runat="server" CssClass="lbl" Text="Last
Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server" Font-Size="14px" ></asp:TextBox>
</td>
</tr>
<tr>

<td>
<asp:Label ID="Label3" runat="server" CssClass="lbl" Text="Gender"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server" Font-Size="14px" ></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label4" runat="server" CssClass="lbl" Text="Age"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox4" runat="server" Font-Size="14px" ></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label5" runat="server" CssClass="lbl" Text="City"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox5" runat="server" Font-Size="14px" ></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label6" runat="server" CssClass="lbl" Text="State"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox6" runat="server" Font-Size="14px" ></asp:TextBox>
</td>
</tr>
</table>
<br />
<asp:Button ID="Button2" runat="server" Text="Close" />
</asp:Panel>
</form>
</body>
</html>
Output
On running the application you will see a simple button that is used to open the popup.

Now a popup window will be opened on which you can fill in the entries, you will see that
the background page is also there but you can't work on that until you close this popup.

Just Add another button and name it as Save button then go on code behind and on click
of this button provide the SQL connection and save it in DB.

Determine Age Using Ajax Calendar in


ASP.Net Application
Step 1
You need to first download the AjaxControlToolkit. Then add the Toolkit to the Bin folder of
your application. Then go to the application and right-click on References to Add
Reference.

Then you need to browse to the Bin folder of your application and select the DLL of the
Ajax Toolkit and click "Ok" Now the AjaxToolkit is added to your application.

Now go to the Toolbox. You will there find an option named "Ajax Extensions". Right-click
on it and click on "choose Items".

A new Wizard will be opened, here if the Ajax Tools already exist then there is no need to
do anything else if Ajax Tools are not showing then click on the Browse button and again
go to the Bin folder, again select the DLL of the AjaxToolkit and click on the "Ok" button.

Step 2

Now we will work on the ".aspx.cs" page of our application. Here we will first register the
Assembly of Ajax Toolkit. To do that write this single line of code:
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefi
x="cc1" %>
Now write this code in the application:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<table>
<tr>
<td>
<asp:Label ID="Label7" runat="server" CssClass="lbl1" Text="Date Of Birth"></asp:L
abel>
</td>
<td >
<cc1:CalendarExtender runat="server" TargetControlID="txtDATE_OF_BIRTH" Forma
t="yyyy-MM-dd" OnClientDateSelectionChanged="SelectDate" I
D="CalendarExtender1"></cc1:CalendarExtender>
<script type="text/javascript">
function SelectDate(e) {
var PresentDay = new Date();
var dateOfBirth = e.get_selectedDate();
var months = (PresentDay.getMonth() - dateOfBirth.getMonth() + (12 * (Presen
tDay.getFullYear() - dateOfBirth.getFullYear())));
alert("You Are Of " + Math.round(months / 12) + " Years");
document.getElementById("txtCONSULTANT_AGE").value = Math.round(months
/ 12);
}
</script>
<asp:TextBox ID="txtDATE_OF_BIRTH" runat="server" Font-Size="12px" ><
/asp:TextBox>
<br />
<label id="Label34" runat="server" style="color:Gray; font-size:9px">Focus on Textbo
x to see Calender</label>
</td>
</tr>
<tr>
<td >
<asp:Label ID="Label35" runat="server" CssClass="lbl1" Text="Age"></asp:Label>
</td>
<td >
<asp:TextBox ID="txtCONSULTANT_AGE" ReadOnly="true" runat="server" FontSize="12px" ></asp:TextBox>
</tr>
</table>
</form>
</body>
</html>
Here first I have added the Script Manager necessary for are working on the Ajax Tools.
Then I created a table, in the second <td> you can see that I hae used
"cc1:CalenderExtender". "cc1" is the Tag Prefix for the Ajax Toolkit and CalendarExtender
is the Calendar of Ajax. Calendar Extender has some properties that are as follows:

1. TargetControlId: Here we provide the Id of the Tool on which calendar is to be


applied.
2. Format: Here we provide the format depending on which date will be shown.
Here I had used the format in which entries are made in the SQL.
3. OnClientDateSelectionChanged: Here we pass the name of the function that is
working along with this calendar.
Then a function is created named "SelectDate". This function is the main function that
will help us to find the age of the user by subtracting the present date from the date that
was selectred.
I had shown the age by an alert message.
At the end of the function a single line of code is written:
document.getElementById("txtCONSULTANT_AGE").value = Math.round(months / 12);
This code will transfer the age to the Second TextBox automatically,
"txtCONSULTANT_AGE" is the ID of the second TextBox.
I had made a second TextBox as Read Only so that the user can't make the changes in it.
Now your application is created and you can run it to see the output.
Output
On running the application you will get an output like this:

As you will click on the TextBox a calendar will be opened just below the TextBox from
which you need to select your Date of Birth as I had selected.

On selecting the Date of Birth from the Calendar an alert Box will be opened that will
show the age in years.

If you check your second TextBox then you will find that the same number of years are
filled in in the second TextBox also. Since the second TextBox was made readonly the
user can't make changes in it but as the user again change the date by selecting the
DOB from the calendar this TextBox will also be updated.

UpdateProgress Control With UpdatePanel


in AJAX
Ajax (Asynchronous JavaScript and XML) is a new web development technique for
interactive websites. With the help of AJAX we can develop web applications and retrieve
small amounts of data from a web server. AJAX consists of a different type of technology.

JavaScript

XML

Asynchronous Call to the server

UpdateProgress
The UpdateProgress control provides status information about partial-page updates in
UpdatePanel controls. You can customize the default content and the layout of the
UpdateProgresscontrol. To prevent flashing when a partial-page update is very fast, you
can specify a delay before the UpdateProgress control is displayed.
Step 1 : Open Visual Studio 2010.

Go to File->New->WebSite

Select ASP.NET Empty WebSite

Step 2 : Go to Solution Explorer and right-click.

Select Add->New Item

Select WebForm

Default.aspx page open

Step 3 : Go to Default.aspx page and click on the [Design] option and drag control from
Toolbox.

Drag Panel, ScriptManager, TextBox, Label, UpdatePanel, RequireFieldValidator

Step 4 : Now we define ContentTemplate for the UpdatePanel.


ContentTemplate
Code
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>

<asp:Label ID="lblMessage" runat="server" EnableViewState="false" ForeColor="blue


"></asp:Label>
<table border="1">
<tr>
<td>Name</td>
<td><asp:TextBox ID="TextBox1" runat="Server"></asp:TextBox>
<asp:RequiredFieldValidator ID="Req1" runat="server" ControlToValidate="TextBox
1"Text=" * Required"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Address</td>
<td><asp:TextBox ID="TextBox2" runat="Server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"ControlTo
Validate="TextBox2" Text=" * Required"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Phone</td>
<td><asp:TextBox ID="TextBox3" runat="Server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"ControlTo
Validate="TextBox3" Text=" * Required"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>City</td>
<td><asp:TextBox ID="TextBox4" runat="Server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"ControlTo
Validate="TextBox4" Text=" * Required"></asp:RequiredFieldValidator>
</td>
</tr>
<td><b>Notice "Please wait" message below after clicking button.</b></td>
<td>
<asp:Button ID="btnSave" runat="Server" Text="Add Records"
onclick="btnSave_Click" />
</td>
</tr>
</table>
</ContentTemplate>
Step 5 : Now go to the Default.aspx[design] page and drag an UpdateProgress control
from the Toolbox.

Step 6 : Now the following code is given below.


Code
<asp:UpdateProgress ID="Up1" runat="Server" AssociatedUpdatePanelID="UpdatePanel
1">
<ProgressTemplate>
<span style="background-color:#66997A;"> <img src="img/images.jpg" al
t="Please wait" width="100px"/> Please wait ...</span>
</ProgressTemplate>
</asp:UpdateProgress>
Step 7 : Now click on the button control and write some code.
Code
System.Threading.Thread.Sleep(3000);
lblMessage.Text = "Processing completed";
Step 8 : Go to the default.aspx.cs option and write some code.
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(3000);
lblMessage.Text = "Processing completed";
}
}
Step 9 : Now the complete code in Default.aspx[source] page is:

Code
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div style="background-color: #BBC6DD">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblMessage" runat="server" EnableViewState="false" ForeColor="blue
"></asp:Label>
<table border="1">
<tr>
<td>Name</td>
<td><asp:TextBox ID="TextBox1" runat="Server"></asp:TextBox>
<asp:RequiredFieldValidator ID="Req1" runat="server" ControlToValidate="TextBox
1"Text=" * Required"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Address</td>
<td><asp:TextBox ID="TextBox2" runat="Server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"ControlTo
Validate="TextBox2" Text=" * Required"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Phone</td>
<td><asp:TextBox ID="TextBox3" runat="Server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"ControlTo
Validate="TextBox3" Text=" * Required"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>City</td>
<td><asp:TextBox ID="TextBox4" runat="Server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"ControlTo
Validate="TextBox4" Text=" * Required"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td><b>Notice "Please wait" message below after clicking button.</b></td>
<td>
<asp:Button ID="btnSave" runat="Server" Text="Add Records"
onclick="btnSave_Click" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
// UpdateProgress control
<asp:UpdateProgress ID="Up1" runat="Server" AssociatedUpdatePanelID="UpdatePa
nel1">
<ProgressTemplate>
<span style="background-color:#66997A;"> <img src="img/images.jpg" al

t="Please wait" width="100px"/> Please wait ...</span>


</ProgressTemplate>
</asp:UpdateProgress>
</div>
Step 10 : Now run the application by Pressing F5.

Step 11 : When we click on the Add Record button then the following message is shown.

Step 12 : Now we define all require fields and click on the add record button.

Calling an ASP.NET C# Method (Web


Method) Using JavaScript

I will create a simple form having two asp.Net textboxes and a button, we will enter our
name and address in the textboxes and by clicking button will call the code-behind
methods. For this we need to take the advantage of PageMethod and to setup
PageMethod we need instance of ScriptManager on web page.
This is what we are going to create:

PageMethod is an easier and faster approach for ASP.NET AJAX. We can easily improve
the user experience and the performance of web applications by unleashing the power of
AJAX. One of the best things I like in AJAX is the PageMethod.

PageMethod is a way through which we can expose the server side page's methods in
JavaScript. This brings so many opportunities; we can perform many operations without
using slow and annoying post backs.
Let's create our HTML Page:
<div>
<p>Say bye-bey to Postbacks.</p>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="tr
ue"></asp:ScriptManager>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup"OnClientClick="
HandleIT(); return false;" />
</div>
Now, in the above code you can see one instance of the ScriptManager and two
textboxes and a button at the end. In the button control you will see an attribute
'OnClientClick' to fire the JavaScript Method named "HandleIT()" and this JavaScript
Method will call the code-behind C# page method.
Note: Remember to add a new attribute EnablePageMethods and set it to true in the
ScriptManager.
Now, look at the JavaScript Code:
<head runat="server">
<title></title>
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
</head>
In the above code, there is a "HandleIT()" JavaScript Method having two the variables,
name and address. These variables will carry the values of the textboxes. Next, a
PageMethod named "ProcessIT" is being called that passes the two parameters name
and address and the other two parameters will contain the success result and error
result. Next, the definition of these success results.

Now look at the code-behind of the C# (PageMethod):

[WebMethod]
public static string ProcessIT(string name, string address)
{
string result = "Welcome Mr. " + name + ". Your address is '" +
address + "'.";
return result;
}
In the above code, to tell the script manager that this method is accessible through
JavaScript we need to ensure two things. First this method should be "public static".
Second there should be a [WebMethod] tag in the above method as written in the above
code.
Remember to use the namespace "System.Web.Services" for WebMethods.
So, now we are all set to test it.

Update Record in GridView Using Modal


Popup Extender

If you don't have ajaxcontroltoolkit then you can download it from here:
http://ajaxcontroltoolkit.codeplex.com/releases/view/90063
After downloading it install it via toolbox in Visual Studio; create a new tab in toolbox via
right-click and add a new tab, rename it to ajax and then right-click on it and choose item
and then browse to the location where you have downloaded the ajaxcontroltoolkit35.dll
to and add it and click ok.
Save this connection string into you web.config file:
<connectionStrings>
<add name="HoneyConnectionString" connectionString="Data Source=adcpc;Initial Catalog=honey;Integrated
Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<Ajax:ToolkitScriptManager ID="ToolkitScriptManager1"
runat="server"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="EmployeeID"
DataSourceID="SqlDataSource1"
onrowcommand="GridView1_RowCommand" BackColor="White"
BorderColor="#CC9966" BorderStyle="None"
BorderWidth="1px" CellPadding="4" Width="550px">
<RowStyle BackColor="White" ForeColor="#330099" />
<Columns>
<asp:ButtonField Text="Edit" CommandName="OpenPopUp"/>
<asp:BoundField DataField="EmployeeID" HeaderText="ID"
InsertVisible="False" ReadOnly="True"
SortExpression="EmployeeID"/>
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName"/>
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName"/>
<asp:BoundField DataField="Country" HeaderText="Country"
SortExpression="Country"/>
</Columns>
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" /
>
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>

<asp:Label ID="lblMessage" runat="server"/>


<asp:Button ID="btnPopUp" runat="server"
style="display:none" />
<Ajax:ModalPopupExtender ID="modalPopUpExtender1"
runat="server"
TargetControlID="btnPopUp"
PopupControlID="pnlModalPopUp"
BackgroundCssClass="modalBackground"
CancelControlID="btnCancel"
X="20"
Y="100">
</Ajax:ModalPopupExtender>
<asp:Panel runat="Server" ID="pnlModalPopUp" BackColor="Azure"
BorderColor="Beige" BorderStyle="Inset">
<asp:GridView ID="EditGridView" runat="server"
AutoGenerateColumns="False"
DataKeyNames="EmployeeID"
DataSourceID="SqlDataSource2">
<Columns>
<asp:ButtonField Text="Update" CommandName="Update"/>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server"
Text='<%# Bind("FirstName") %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:TextBox ID="txtLastName" runat="server"
Text='<%# Bind("LastName") %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:TextBox ID="txtCountry" runat="server"
Text='<%# Bind("Country") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
onupdated="SqlDataSource2_Updated"
ConnectionString=
"<%$ ConnectionStrings:HoneyConnectionString %>"
SelectCommand="SELECT [EmployeeID], [LastName], [FirstName],
[Country] FROM [normal]
WHERE ([EmployeeID] = @EmployeeID)"
UpdateCommand="UPDATE [normal] SET [LastName] = @LastName,
[FirstName] = @FirstName, [Country] = @Country

WHERE [EmployeeID] = @EmployeeID">


<SelectParameters>
<asp:Parameter Name="EmployeeID" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="EmployeeID" Type="Int32" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="Country" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:Button ID="btnCancel" runat="server"
Text="Cancel"/>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString=
"<%$ ConnectionStrings:HoneyConnectionString %>"
SelectCommand="SELECT [EmployeeID], [LastName],
[FirstName], [Country] FROM [normal]">
</asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Your default.cs file will be like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "OpenPopUp")
{
lblMessage.Text = "";
int rowIndex = Convert.ToInt32(e.CommandArgument);
int id = Convert.ToInt32(GridView1.DataKeys[rowIndex].Value);
SqlDataSource2.SelectParameters["EmployeeID"].DefaultValue = id.ToString();
modalPopUpExtender1.Show();
}
}
protected void SqlDataSource2_Updated(object sender, SqlDataSourceStatusEventArg
s e)
{
GridView1.DataBind();
lblMessage.Text = "Record Updated";
}
Your code will look in design view like this:

And when you click on Edit then a modalpopup will popup and in this window you can
update a record via clicking on the update button or you cancel the update. The following
is the modalpopup window.

Just Change the field value you want and the output will be like this below:

http://www.onlinebuff.com/article_step-by-step-to-use-stored-procedures-inaspnet-c-with-example_49.html
http://blog.sqlauthority.com/2016/05/08/list-stored-procedure-modified-last-daysinterview-question-week-070/
http://www.onlinebuff.com/article_step-by-step-partial-classes-and-partialmethods-in-cnet-with-example_58.html
http://www.onlinebuff.com/article_understand-difference-between-early-bindingand-late-binding-with-an-example-in-c_55.html
http://www.onlinebuff.com/article_what-is-an-indexer-explain-how-it-is-differentfrom-property-in-terms-of-implementation_26.html
http://www.onlinebuff.com/article_understanding-switch-statement-with-the-helpof-an-example_24.html
http://www.onlinebuff.com/article_understanding-the-concept-of-pass-by-valueand-pass-by-reference-with-an-example_22.html
http://www.onlinebuff.com/article_implementing-interface-in-c-with-anexample_18.html
http://www.onlinebuff.com/article_oops-principle-inheritance-in-c-with-anexample_16.html
http://www.onlinebuff.com/article_explain-the-copy-and-private-constructor-withan-example-in-c_13.html
http://www.onlinebuff.com/article_oops-principle-abstraction-in-c-with-anexample-and-explanation_5.html

http://www.onlinebuff.com/article_what-are-delegates-in-c-step-by-step-creatingand-using-the-delegate_4.html
http://www.onlinebuff.com/article_understanding-the-relationships-inheritanceassociation-aggregation-and-composition-in-c_20.html
http://www.onlinebuff.com/article_difference-between-for-loop-and-for-each-loopin-csharp_1.html
http://www.onlinebuff.com/article_what-is-a-constructor-in-c-and-list-types-ofconstructors-in-c_19.html
http://www.onlinebuff.com/article_what-are-structures-differentiate-betweenstructures-and-classes_23.html
http://manish4dotnet.blogspot.in/2012/05/page-life-cycle-in-aspnet.html
http://w3asp.net/923/asp.net/article/explain-asp.net-page-life-cycle-events-withexample
https://dotnetinterviewquestion.wordpress.com/2013/03/12/c-interviewquestions-and-answers-explain-the-use-of-icomparable-in-c/

How can we check which rows have changed since dataset


was loaded?
http://saivideo.blogspot.in/2013/05/silver-u-neat-way-to-remember-aspnet.html
http://codedisplay.com/asp-net-or-aspx-page-life-cycle-interview-question/
http://www.etechpulse.com/2013/04/all-about-page-life-cycle-with-example.html
http://computerauthor.blogspot.in/2013/03/net-interview-questions-andanswers.html
In the try statement we have a return statement, will the finally block still run.

The stsges of Page life cycle are as follows :

Methods
Page_Init
LoadViewState
LoadPostData
Page_Load
RaisePostDataChangedEvent
RaisePostBackEvent
Page_PreRender
SaveViewState
Page_Render
Page_Unload

Description
Page Initialization
View State Loading
Postback Data Processing
Page Loading
PostBack Change Notification
PostBack Event Handling
Page Pre Rendering Phase
View State Saving
Page Rendering
Page Unloading

How to use C# string Split

How to split strings using regular expressions


The Regular Expressions Split() methods are almost similar to the
String.Split() method, except that Regex.Split() method splits the
string at a delimiter determined by a Regular Expression instead
of a set of characters.
When using Regular Expressions you should use the following
namespace in your project
using System.Text.RegularExpressions;
string str = "one\n
\ntwo\n
\nthree\n
\n
string[] result = Regex.Split(str, "\n\\s*");
for (int i = 0; i < result.Length; i++)
MessageBox.Show(result[i]);

\nfour";

Output:
one
two
three
four

Using Regular Expressions for multiple characters


C# String Split by multiple characters delimiter using Regular
Expressions
string input = "one)(two)(three)(four)(five";
string[] result = Regex.Split(input, @"\)\(");
foreach (string s in result)
MessageBox.Show(s);

Output:
one
two
three
four
five

Regular Expressions Usage in C#

Regular expressions are used to search specified in the source string.


Examples:
Pattern#1
Regex objNotNaturalPattern=new Regex("[^0-9]");
Pattern#2
Regex objNaturalPattern=new Regex("0*[1-9][0-9]*");
Pattern#1 will match for strings other than 0 to 9.^ symbol is used for
Specifying not condition.[] brackets if we are to give range values such as
0 - 9 or a-z or A-Z
eg. abc will return true
123 will return false.
Pattern#2 will match for string which are Natural Numbers. Natural
numbers Are numbers which are always greater than 0.The pattern 0*
tells that a natural Number can be prefixed with any number of zero's or
no zeros. The next [1-9] tells that it should contain at least one number
from 1 to 9 followed by any numbers of
0-9's
Eg. 0007 returns true whereas 00 will return false.
Basic things to be understood in RegEx:
"*" matches 0 or more patterns
"?" matches single character
"^" for ignoring matches.
"[]" for searching range patterns.
Source Code:
// Source Code starts
using System.Text.RegularExpressions;
using System;
/*
<HowToCompile>
csc /r:System.Text.RegularExpressions.dll,System.dll Validation.cs

</HowToComplie>
*/
class Validation
{
public static void Main()
{
String strToTest;
Validation objValidate=new Validation();
Console.Write("Enter a String to Test for Alphabets:");
strToTest=Console.ReadLine();
if(objValidate.IsAlpha(strToTest))
{
Console.WriteLine("{0} is Valid Alpha String",strToTest);
}
else
{
Console.WriteLine("{0} is not a Valid Alpha String",strToTest);
}
}
// Function to test for Positive Integers.
public bool IsNaturalNumber(String strNumber)
{
Regex objNotNaturalPattern=new Regex("[^0-9]");
Regex objNaturalPattern=new Regex("0*[1-9][0-9]*");
return !objNotNaturalPattern.IsMatch(strNumber) &&
objNaturalPattern.IsMatch(strNumber);
}
// Function to test for Positive Integers with zero inclusive
public bool IsWholeNumber(String strNumber)
{
Regex objNotWholePattern=new Regex("[^0-9]");
return !objNotWholePattern.IsMatch(strNumber);
}
// Function to Test for Integers both Positive & Negative
public bool IsInteger(String strNumber)
{
Regex objNotIntPattern=new Regex("[^0-9-]");
Regex objIntPattern=new Regex("^-[0-9]+$|^[0-9]+$");
return !objNotIntPattern.IsMatch(strNumber) && objIntPattern.IsMatch(strNumber);
}

// Function to Test for Positive Number both Integer & Real


public bool IsPositiveNumber(String strNumber)

{
Regex objNotPositivePattern=new Regex("[^0-9.]");
Regex objPositivePattern=new Regex("^[.][0-9]+$|[0-9]*[.]*[0-9]+$");
Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*");
return !objNotPositivePattern.IsMatch(strNumber) &&
objPositivePattern.IsMatch(strNumber) &&
!objTwoDotPattern.IsMatch(strNumber);
}
// Function to test whether the string is valid number or not
public bool IsNumber(String strNumber)
{
Regex objNotNumberPattern=new Regex("[^0-9.-]");
Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*");
Regex objTwoMinusPattern=new Regex("[0-9]*[-][0-9]*[-][0-9]*");
String strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
String strValidIntegerPattern="^([-]|[0-9])[0-9]*$";
Regex objNumberPattern =new Regex("(" + strValidRealPattern +")|(" +
strValidIntegerPattern + ")");
return !objNotNumberPattern.IsMatch(strNumber) &&
!objTwoDotPattern.IsMatch(strNumber) &&
!objTwoMinusPattern.IsMatch(strNumber) &&
objNumberPattern.IsMatch(strNumber);
}
// Function To test for Alphabets.
public bool IsAlpha(String strToCheck)
{
Regex objAlphaPattern=new Regex("[^a-zA-Z]");
return !objAlphaPattern.IsMatch(strToCheck);
}
// Function to Check for AlphaNumeric.
public bool IsAlphaNumeric(String strToCheck)
{
Regex objAlphaNumericPattern=new Regex("[^a-zA-Z0-9]");
return !objAlphaNumericPattern.IsMatch(strToCheck);
}
}

.NET Regular Expressions

The Regexp classes are allowed to use regular expressions in .NET. All
classes are contained in the System.Text.RegularExpressions assembly,
and you will have to reference the assembly at compile time in order to
build your application. For example: csc
/r:System.Text.RegularExpressions.dll foo.cs will build the foo.exe
assembly, with a reference to the System.Text.RegularExpressions
assembly.
There are only six classes and one delegate which it is necessary to
overview:

Capture: Contains the results of a single match

CaptureCollection: A sequence of Capture's

Group: The result of a single group capture, inherits from Capture

Match: The result of a single expression match, inherits from Group

MatchCollection: A sequence of Match's

MatchEvaluator: A delegate for use during replacement operations

Regex: An instance of a compiled regular expression

The Regex class also contains several static methods:

Escape: Escapes regex metacharacters within a string

IsMatch: Methods return a boolean result if the supplied regular


expression matches within the string

Match: Methods return Match instance

Matches: Methods return a list of Match as a collection

Replace: Methods that replace the matched regular expressions with


replacement strings

Split: Methods return an array of strings determined by the


expression

Unescape: Unescapes any escaped characters within a string

Example.

using System.Text.RegularExpressions;
using System;
namespace RegularExpressionsSample
{
class Program
{
static void Main(string[] args)
{
string regularExpression = "s[ia]mple";
string inputString = "Is it simple sample?";
Match m = Regex.Match(inputString, regularExpression);
Console.WriteLine("Match = " + m.ToString());
Console.WriteLine("Next match = " + m.NextMatch().ToString());
}
}
}
Output:
Match = simple
Next match = sample
Regular Expression Options:
Regular Expression Options can be used in the constructor for the Regex
class.

RegexOptions.None - Specifies that no options are set.

RegexOptions.IgnoreCase - Specifies case-insensitive matching.

RegexOptions.Multiline - Multiline mode. Changes the meaning of ^


and $ so they match at the beginning and end, respectively, of any
line, and not just the beginning and end of the entire string.

RegexOptions.Singleline - Specifies single-line mode. Changes the


meaning of the dot (.) so it matches every character (instead of
every character except \n).

RegexOptions.ExplicitCapture - Specifies that the only valid captures


are groups that are explicitly named or in the form (?<name>...).

RegexOptions.IgnorePatternWhitespace - Eliminates unescaped


white space from the pattern and enables comments marked with
the hash sign (#).

RegexOptions.Compiled - Specifies that the regular expression is


compiled to an assembly. The regular expression will be faster to
match but it takes more time to compile initially. This option
(although tempting) should only be used when the expression will
be used many times. e.g. in a foreach loop

RegexOptions.ECMAScript - Enables ECMAScript-compliant behavior


for the expression. This flag can be used only in conjunction with
the IgnoreCase, Multiline, and Compiled flags. The use of this flag
with any other flags results in an exception.

RegexOptions.RightToLeft - Specifies that the search will be from


right to left instead of from left to right.

Bases of syntax of regular expressions


I will not begin to try to write the full directory on all symbols used in
patterns of regular expressions. For this purpose there is MSDN. Here we
will result only the basic metasymbols. In double inverted commas the
values which are given out by regular expressions, and in unary - syntax
of regular expressions will be used further.
In C# metasymbols which you wish to use not as those and as actually
symbols, should be covered by an escape-symbol \ as in C++ (in other
languages can be differently, for example, in VB it is not necessary). That
is, to find "[" , it is necessary to write '\['.The symbol \ means, that the
symbol following it is special symbol, a constant and so on. For example,
'n' means the letter "n." '\n' means a symbol of a new line. The sequence
'\\' corresponds "\", and '\(' corresponds "(".
Classes of symbols (Character class)
Using square brackets, it is possible to specify group of symbols (it name
a class of symbols) for search. For example, the design 'b[ai]rge' would
correspond to words "barge" and "birge", i.e. the words beginning with
"b" which follow "a" or "i", and coming to an end on "rga". Probably and
the return, that is, it is possible to specify symbols which should not
contain in found substring. So, '[^1-6]' finds all symbols, except for
figures from 1 up to 6. It is necessary to mention, that inside of a class of
symbols '\b' designates a symbol backspace (deletings).

Quantifiers
If it is not known, how many signs should contain required substring, it is
possible to use special symbols, called by an odd word quantifiers. For
example, it is possible to write "hel+o", that will mean a word beginning
with "he", with following for it one or the several "l", and coming to an
end on "o". It is necessary to understand, that quantifier concerns to
previous expression, instead of a separate symbol.
Symbo
l
*
+
?
*?
+?
{n}

Overview
Corresponds 0 or more occurrences of previous expression.
For example, 'zo*' corresponds "z" and "zoo".
Corresponds 1 or more previous expressions.
For example, 'zo+' corresponds "zo" and "zoo", but not "z".
Corresponds 0 or 1 previous expressions.
For example, 'do(es)?' corresponds "do" in "do" or "does".
Corresponds 0 or more previous expressions as few characters as possible.
For example, 'dog*?' corresponds "do" in "do" or "does"
Corresponds 1 or more previous expressions as few characters as possible.
For example, 'dog+?' corresponds "dog" in "dog" or "dogger".
n - the non-negative whole. Corresponds to exact quantity of occurrences.
For example, 'o{2}' will not find "o" in "Bob", but will find two "o" in "food".
n - the non-negative whole. Corresponds to the occurrence repeated not less n
of time.

{n,}

For example, 'o{2,}' does not find "o" in "Bob", but finds all "o" in "foooood".
'o{1,}' it is equivalent 'o+'.
'o{0,}' it is equivalent 'o*'.
m and n - non-negative integers, where n <= m. There corresponds a minimum
n and a maximum m occurrences.

{n,m}

For example, 'o{1,3}' finds three first "o" in "fooooood".


'o{0,1}' it is equivalent 'o?'.
The blank space between a comma and figures is inadmissible.

When between two characters or groups, matches one or the other (this is
called an alternating operation, because it chooses among two alternatives).

Table 1. Quantifiers.
The important feature of quantifiers '*' and '+' is their greed. They find
everything that can - instead of that is necessary.
Example.

Source string - "hello out there, how are you"


Regular expression - 'h.*o'
It means to search 'h' which any symbols which follows 'o' follow some. In a kind,
probably, was available "hello", but it will be found "hello out there, how are you"
- because of greed of the regular expression looking not first, but last "o". To cure
quantifier of greed it is possible, having added '?'. That is,
Source string - "hello out there, how are you"
Regular expression - 'h.*?o'
will find "hello", as it was necessary, as searches 'h' which any symbols follow
some, up to the first met 'o'.

The ends and the beginnings of strings


Check has begun the ends or the end of a line is made by means of
metasymbols ^ and $. For example, '^thing' corresponds to a line
beginning with "thing". 'thing$' corresponds to a line which is coming to
an end on "thing". These symbols work only at the included option 's'. At
the switched off option 's' there is only an end and the beginning of the
text. There is also a symbol \z, an exact end of a line.
Border of a word
For the task of borders of a word metasymbols '\b' and '\B' are used.
Regular expression 'out' corresponds not only "out" in "speak out loud",
but also "out" in "please do not shout at me". To avoid it, it is possible to
anticipate the sample a marker of border of a word.
With the expression '\bout' it will be found only "out" in the beginning of a
word. It is necessary, that inside of a class of symbols '\b' designates a
symbol backspace (deletings).
Other special characters
In the table below I have displayed other special symbols:
Symbol Overview
\a

Matches a bell (alarm).

\b

Matches a backspace if in a [] character class; otherwise, see above.

\t

Matches a tab.

\r

Matches a carriage return.

\v

Matches a vertical tab.

\f

Matches a form feed.

\n

Matches a new line.

\e

Matches an escape.

\w

Matches a character(a-z, A-z, 0-9 and underscore).

\W

Matches any character that is not a letter.

\s

Matches any white spaces(space or tab).

\S

Matches any character that is not white space.

\d

Matches a digit(0-9).

\D

Matches any character that is not a digit.

Matches any character, except the end of line or the end of text.

Matches the end of the string or line.

Table 2. Other special symbols


Grouping and Backreferences
You can group patterns by placing them in parenthesis. You can give a
name to the group as well. Here are some of the grouping constructs
you'll be using:
Constructio
n

Overview

()

Defines a simple group.

(?<name>)

Group named "name"

(?i:)

Igonre case when matching within the group

\n

Matches a previous group(group #n)


For example, (\w)\1 finds doubled word characters.
Matches a previous group with the specified name.

\k<name>

For example, (?<char>\w)\k<char> finds doubled word characters. The


expression (?<43>\w)\43 does the same. You can use single quotes
instead of angle brackets; for example, \k'char'.

Table 3. Grouping patterns


Groups that don't have a name, have a number.
Example.
using System.Text.RegularExpressions;
using System;
namespace RegularExpressionsSample
{

class Program
{
static void Main(string[] args)
{
// Should match everything except the last two.
string regularExpression = @"\$(\d+)\.(\d\d)";
string inputString = "$1.57 $316.15 $19.30 $0.30 $0.00 $41.10 $5.1 $.5";
for (Match m = Regex.Match(inputString, regularExpression); m.Success; m =
m.NextMatch())
{
GroupCollection gc = m.Groups;
Console.WriteLine("The number of captures: " + gc.Count);
// Group 0 is the entire matched string itself
// while Group 1 is the first group to be captured.
for (int i = 0; i < gc.Count; i++)
{
Group g = gc[i];
Console.WriteLine(g.Value);
}
}
}
}
}
Output:
The number
$1.57
1
57
The number
$316.15
316
15
The number
$19.30
19
30
The number
$0.30
0
30
The number

of captures: 3

of captures: 3

of captures: 3

of captures: 3

of captures: 3

$0.00
0
00
The number of captures: 3
$41.10
41
10
Replacement
Substitutions are allowed only within a replacement pattern. For similar
functionality within a regular expression, use a backreference such as \1.
Character escapes and substitutions are the only special constructs
recognized in a replacement pattern. All other syntactic constructs are
allowed in regular expressions only and not recognized in replacement
patterns. For example, the replacement pattern 'a*${test}b' inserts the
string "a*" followed by the substring matched by the "test" capturing
group, if any, followed by the string "b". The * character is not recognized
as a metacharacter within a replacement pattern. Similarly, $-patterns are
not recognized within a regular expression matching pattern. Within a
regular expression, $ denotes the end of the string. Other examples are:
'$123' substitutes the last substring matched by group number 123
(decimal), and ${name} substitutes the last substring matched by a (?
<name>) group.
Example.
Formatting string with replace method.

using System.Text.RegularExpressions;
using System;
namespace RegularExpressionsSample
{
class Program
{
static void Main(string[] args)
{
string regularExpression = @"(\s*)Dim\s+(\w+)\s+As\s+(\w+)";
string inputString = "Dim abc As Integer";
string replacement = "$1$3 $2;";
Console.WriteLine(Regex.Replace(inputString, regularExpression, replacement));
}

}
}
Output:
Integer abc;
Lookaround
There are two directions of lookaround - lookahead and lookbehind - and
two flavors of each direction - positive assertion and negative assertion.
The syntax for each is:

(?=...) - Positive lookahead

(?!...) - Negative lookahead

(?<=...) - Positive lookbehind

(?<!...) - Negative lookbehind

Understanding look(ahead|behind) requires an understanding of the


difference between matching text and matching position. To help with this
understanding I should state first that lookaround assertions are nonconsuming. To see what I mean, let's look at the following simple
example.
regularExpression = "stop";
inputString = "stopping";
When the above pattern is applied to the text the "context" of the parser
sits at a position in the text between the "s" and the "i" in the word
stopping. This is because the regular expression parser bumps along the
string as it gets a match, like so:

Start - ^stopping

Match "s" - ^topping

Match "t" - s^opping

Match "o" - st^pping

Match "p" - sto^ping

Once the parser has moved beyond a position there is no way to reverse
up and re-attempt a match. To understand where this causes difficulty,
consider this, what if you needed to match the word "stop" but only when
it was contained in the word "stopped" and not any other possible
combination such as "stopper". With lookahead you can simply assert that
condition like so: (?=stopped\b)stop
This works because, with lookaround, the parser is not bumped along the
string. This can be especially useful for finding a position in a document
by combining a lookahead assertion with a lookbehind assertion. To
demonstrate, let's consider that we need to match the string "stop" when
it was contained within the string "estopped" but not "astopped". To do
this you can do a negative, lookbehind assertion on "a" and a positive
lookahead assertion on "stopped", like this: (?<!a)(?=stopped\b)stop
In other words you are matching a position at which to start matching
text. The above pattern would set the parser at the following position in
the string "estopped"
Start - e^stopped
Match "s" - e^topped
Match "t" - es^opped
Match "o" - est^pped
Match "p" - esto^ped
Example.
Example of using lookaround would be to validate "special" password
conditions such as: "Password must be between 8 and 20 characters,
must contain at least 2 letter characters and at least 2 digit characters. It
can only contain either letter or digit characters."
For such a password constraint, the following expression would probably
do quite nicely: ^(?=.*?\d.*?\d)(?=.*?\w.*?\w)[\d\w]{8,20}$
using System.Text.RegularExpressions;
using System;
namespace RegularExpressionsSample
{
class Program
{
static void Main(string[] args)
{

string regularExpression = @"^(?=.*?\d.*?\d)(?=.*?\w.*?\w)[\d\w]{8,20}$";


Console.WriteLine("Please input password for check:");
string inputString = Console.ReadLine();
if (inputString != "" && Regex.IsMatch(inputString, regularExpression))
{
Console.WriteLine("It's correct security password");
}
else
{
Console.WriteLine("It's incorrect password.");
}
Console.Read();
}
}
}
Output:
Please input password for check:
abc4D5678
It's correct security password
The most actual regular expression patterns
Pattern

Description
This expression matches email addresses, and

^[\w-\.]+@([\w-]+\.)+[\w-]

checks that they are of the proper form. It checks

{2,4}$

to ensure the top level domain is between 2 and 4


characters long.
A regular expression to match phone numbers,

^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$

allowing for an international dialing code at the


start and hyphenation and spaces that are
sometimes entered.
This regular expressions matches dates of the form

^\d{1,2}\/\d{1,2}\/\d{4}$

XX/XX/YYYY where XX can be 1 or 2 digits long and


YYYY is always 4 digits long.

^([0-1][0-9]|[2][0-3]):([0-5][0-

This regular expressions matches time in the format

9])$

of HH:MM

\b(([01]?\d?\d|2[0-4]\d|25[05])\.){3}([01]?\d?\d|2[0-4]\d|

This regular expressions matches Decimal IPs.

25[0-5])\b
^\d{5}$|^\d{5}-\d{4}$

This regular expression will match either a 5 digit

ZIP code or a ZIP+4 code formatted as 5 digits, a


hyphen, and another 4 digits.
This regular expression will match a hyphen^\d{3}-\d{2}-\d{4}$

separated Social Security Number (SSN) in the


format NNN-NN-NNNN.
Matches major credit cards including: Visa (length

^((4\d{3})|(5[1-5]\d{2})|
(6011))-?\d{4}-?\d{4}-?\d{4}|
3[4,7]\d{13}$

16, prefix 4), Mastercard (length 16, prefix 51-55),


Discover (length 16, prefix 6011), American
Express (length 15, prefix 34 or 37). All 16 digit
formats accept optional hyphens (-) between each
group of four digits.

(http|https|ftp)\://[a-zA-Z0-9\-\.]
+\.[a-zA-Z]{2,3}(:[a-zA-Z09]*)?/?([a-zA-Z
0-9\-\._\?\,\'/\\\+&%\$#\=~])*

This regular expression will match some URL.