Sie sind auf Seite 1von 90

INDEX

Chapter - 1 Introduction
Chapter 2 The Development Environment
Chapter - 3 Server Controls
Chapter - 4 Navigation Controls
Chapter - 5 Validation Controls
Chapter - 6 Login Controls
Chapter 7 MasterPage / Theme / CSS
Chapter 8 ADO .NET
Chapter - 9 State Management

Chapter -1 Introduction
According to Microsoft, "ASP.NET is a technology for building powerful, dynamic Web
applications and is part of the .NET Framework". This tutorial will teach you ASP.NET
from scratch, and no knowledge of any kind of server side scripting is required.
Basic HTML and CSS knowledge is preferable. Having worked with Classic ASP or
PHP won't give you much of an advantage, since ASP.NET is a whole new way of
doing
things.
.NET is language independent, which means you can use any .NET supported
language to make .NET applications. The most common languages for writing
ASP.NET applications are C# and VB.NET. While VB.NET is directly based VB (Visual
Basic), C# was introduced together with the .NET framework, and is therefore a
some what new language. Some people call C# "the .NET language", but according
to Microsoft, you can do all the same things, no matter if you're using C# or VB.NET.
The 2 languages are not that different, and if you have used one of them, you will
have no problems at all learning the other. In this tutorial we will use C#.
One of the main differences between ASP.NET and Classic ASP/PHP is the fact that
ASP.NET is compiled, while Classic ASP is always interpreted. PHP can be compiled
by using commercial products, but usually it's interpreted as well.
This tutorial will use the free Visual Web Developer IDE from Microsoft. Despite what
some people think, ASP.NET can be used without an IDE. It would be perfectly
possible to write ASP.NET code in Notepad, and use the commandline compiler
included with the .NET framework. Some people might actually prefer this "back to
basics" way of doing things, but I believe that ASP.NET is best programmed with a
decent IDE. You can use an IDE from another vendor, and you will still be able to
follow most of this tutorial.

The Microsoft .NET Framework


The .NET Framework is the infrastructure for the Microsoft .NET platform.
The .NET Framework is an environment for building, deploying, and running Web
applications and Web Services.
Microsoft's first server technology ASP (Active Server Pages), was a powerful and
flexible "programming language". But it was too code oriented. It was not an
application framework and not an enterprise development tool.
The Microsoft .NET Framework was developed to solve this problem.
.NET Frameworks keywords:

Easier and quicker programming

Reduced amount of code

Declarative programming model

Richer server control hierarchy with events

Larger class library

Better support for development tools

The .NET Framework consists of 3 main parts:


Programming languages:

C# (Pronounced C sharp)

Visual Basic (VB .NET)

J# (Pronounced J sharp)

Server technologies and client technologies:

ASP .NET (Active Server Pages)

Windows Forms (Windows desktop solutions)

Compact Framework (PDA / Mobile solutions)

Development environments:

Visual Studio .NET (VS .NET)

Visual Web Developer

Web Application Architecture:


Web applications have been around for a while now. Because you are
reading a book on how to build web applications, we assume you have
some understanding of how the Internet and web applications work, so
this discussion is only a cursory exploration. However, if you find yourself
thirsty for more information on this subject, numerous resources are at
your disposal.

ASP.NET Runtime:
When we build applications for the web using ASP.NET, we need to have the
ASP.NET run- time installed. This background process is constantly running
on the web server listening for requests that require its services. You can
see this process running in your task manager as aspnet_wp.exe (ASP.NET

worker process). When the web server receives a request, that is, for an
ASP.NET item such as an .aspx page or an .asmx web service, it forwards
the request to the ASP.NET worker process because that is the process
registered as knowing how to handle such requests. If you use Task
Manager by right-clicking your program bar, you can see aspnetwp.exe in
the list of processes. A program registered to handle web requests like this
is known as an Internet Services Application Programming Interface (ISAPI).
The worker process then parses the page being requested and processes
any server-side script that is necessary to derive the final page output (the
response), including any code associated with the page (e.g., C#, VB .NET,
etc.).

Working of an ASP.NET Application


You create an ASP.NET application by using the tools
integrated with the
Miscrosoft .NET Framework. After you create an ASP>NET application, the ASP.NET
files need to be stored on an IIS server, which is the Web server for the Windows
platform. An IIS server processes the ASP>NET files from top to bottom and then
executes the scripts. Finally , the results are sent to the Web browser that requested
the ASP.Net file.
As depicted in the preceding diagram, to execute and ASP.Net file, the following
steps are taken:
1. A Web brewser sends request for an ASP>NET file to a Web server by using a
Uniform Resource Locator(URL).
2. The Web server, IIS receives the request and retrieves the appropriate
ASP.NET file from the disk or memory.
3. The Web server forwards the ASP.NET file to the ASP.NET script engine for
processing.
4. The ASP.Net script engine reads the file from top to bottom and executes any
server side script it eccounters.
5. The processed ASP>NET file is generated as an HTML document , and the
ASP.NET script engine sends the HTML page to the Web server.
6. The Web server then sends the HTML page to the client.
7. The Web browser interprets the output and displays it.
A Web server generates and sends only the HTML output to the client. As a
result, it helps to hide the code of the ASP.Net file from the users who access and
ASP.Net Web page.

Features of ASP.NET:
In addition to hiding script commands , ASP>NET has the following advanced
features that help develop robust Web applications:
Compiled Code: The code written in ASP.NET is compiled and not interpreted.
This makes ASP>NET applications faster to execute than other server side
scripts that are interpreted, such as the scripts written in a previous version
of ASP.
Enriched Tool Support : The ASP.Net Framework is provided with a rich
toolbox and designer in the Visual Studio .NET IDE. Some of the features of
this powerful tool are the what you see is what you get(WYSIWYG) editor,
drag- and drop server controls, and automatic deployment.
Power and Flexibility: ASP.NET applications are based on CLR. As a result, the
pwer and flexibility of the .Net platform is available to ASP.Net application
developers. ASP.Net applications enable you to ensure that the .NET

Framework class library, messaging, and data access solutions are seamlessly
accessible on the Web. ASP.NET is also language-independent. As a result,
you can choose and .NET language to develop your application.
Simplicity: ASP.NET enables you to build user interfaces that separate
application logic from presentation content. In addition, CLR simplifies
application development by using managed code services, such as automatic
reference counting and garbage collection. For this reason, ASP.Net makes it
easy to perform common tasks ranging from form submission and client
authentication to Web site configuration and deployment.
Manageability: ASP.Net enables you to manage Web applications by storing
the configuration information in an Extensible Markup Language(XML) file.
You can open theXML file in the Visual Studio .NET IDE.
Scalability: ASP.NET has been designed with scalability in mind. It has
features that help improve performance in a multiprocessor environment.
Security: ASP.NET provides a number of options for implementing security
and restricting user access to a Web application. All these options are
configured within the configuration file.
Extensibility: ASP.NET provides a number of options to create an extensible
Web application. For example, you can create custom controls; extends the
default Hypertext Markup Language(HTTP) pipeline. Note that the path
through which the data flows from the client to the server is called the HTTP
pipeline.

Programming Models in ASP.Net:


ASP.NET provides two types of programming models:
Web Forms: Enable you to create the user interface for a Web application
.You user server controls to design the user interface of a Web application and
then write coe that will be executed at the server side, to handle the events
triggered by these controls.
Web Services : Enable you to remotely access certain functions at the
server side. These services enable the exchange of data in a client to-server
or a server-to-server environment over the Web by using the Simple Object
Access Protocol(SOAP).
Web Forms:
You can create dynamic Web forms by using technologies such as JSP and
ASP.NET. Notice that the creation of Web forms by using ASP.NET has the following
advantages over other technologies:
Web forms can be designed and programmed using Rapid Application
Development(RAD) tools.
Web forms support a rich set of controls, including user-defined and third
party controls that make the application user-friendly.
Web Forms cab be programmed using any of the .NET Frameword languages,
such as C# or Visual Basic .NET.
In ASP.NET , Web forms consist of a user interface and application logic that is
applied to the components of user interfaces.
A user interface consists of static HTML or XML elements and ASP.NET server
controls. When you create a Web application, the HTML or XML elements and server
controls are saved in a file with .aspx extension. This file is called a page file.
Application logic consists of code that is applied to the user interface elements of a
Web Form page. You can use any of the .NET programming languages, such as
Visual Basic .NET or C# , to write the logic for a Web page.

The Visual Studio .Net IDE provides two different views of a Web form:
Design view
HTML view
Design View:
The Design view represents the user interface of the Web forms page. You can
directly place controls from the toolbox to the Web forms page in the Design view.
By default , the page layout of the Web forms page is GridLayout. You can change
the page layout ot FLopwLayout in the DOCUMENT Properties dialog box. To open
the DOCUMENT Properties dialog box, right-click the page in the Design view and
select Properties from the shortcut menu.
The following figure displays the Design view of an ASP.NET page, which contains a
text box, label, and command button:
Diagram:

HTML View:
The HTML view represents HTML code of an ASP.NET Web form. To opent he
HTML view, click the HTML tab in the designer. If the Web application project is a
Visual Basic project, the scripting language used on the HTML page is Visual Basic. If
the Web application project is a C# project , the scripting language used on the
HTML page is C#.
The following figure displacys the HTML view of the page that was displayed
in the DESIGN view in the preceding figure:
Diagram:

Understanding the Automatically Generated Code:


Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Web;
Using System.Web.SessionsState;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.HtmlControls;
Namespace WebApplication1
{
/// <summary>
/// Summary description for WebForm1.
// / </summary>
Public class WebForm1:System.Web.UI.Page
{
Private void Page_Load(object sender, System.EventArgs e)
{
//put user code to initialize the page here
}
}
}
Namespace
Descriptions
System
Contains classes for implementing base data types.
In addition , it contains classes for working with
date and time.
System.Collections
Contains classes for working with standard
7

System.ComponentModel
System.Data
System.Drawing
System.Web
System.Web.SessionState
System.Web.UI
System.Web.UI.WebControls
System.Web.UI.HtmlControl
s

collection types, such as hash tables and array lists.


Contains classes for implementing both the designtime and run-time behaviors of components and
controls.
Contains classes for implementing the ADO.NET
Architecture.
Contains classes for providing access to the GDI +
basic graphics functions and manipulating the
contents of strings.
Contains classes and
interfaces that enable
browser/server communication.
Contains class for implementing session states.
Contains the base classes used in building the suer
interfaces of the ASP.NET page.
Contains classes for providing Web controls.
Contains classes for providing HTML controls.

Page Events:
ASP.Net
users an event-driven model of programming. This model of ASP.NET
defines a sequence of events that are fired during the life cycle of a Web page.
The following table lists some of these events:
Event
Init
Load
Unload

Generated when
Represents the first event that occurs when the server executes an ASP.NET
page. The initialization is performed during this event. The Init event occurs
only one time in the entire lifecycle of an ASP.NET page
Is fired after the init event, when the page is requested for the first time
and whenever the page is reloaded. This event can be used to initialize the
variables and the state of the controls that are used in the page.
Represents the last event that occurs in the lifecycle of an ASP.NET page.
This event is used to perform final cleanup work, such as the closing of open
database connections, discarding objects, or closing files.

With each event that is raised, you may have some tasks to accomplish. You can
accomplish these tasks by writing code in apecial procedures called event-handing
procedures or simply event handlers. For example, you can write the page
initialization code in the Init or Load event of the Web page. The Page_Init event
handler is the event handler for the Init event of the page, and Page_Load is the
event handler for the Load event of the page. There is a difference between the Init
event and the Load event. When the Init event is fired, the controls are loaded with
their default values. On the other hand, when the Load event is fired, all controls are
loaded in the memory with values that are set during the round trip.A round trip is a
sequence of events that a Web page foillows to complete the journey from a Web
browser to a Web server.
When a user clses the page or exits from the browser, the page is unloaded from the
memory and the unload event is fired. Before the Unload event of a Web page is
fired, the Web page usually undertakes a number of trips form the client to the
server and then back to the client. The trip of a Web page from the client to the
server and then back to the client involves the use of a number of ASP.NET built-inobjects.

First Example
With MS Visual Web Developer installed, we're ready to create our first ASP.NET
website. In VWD, this is very easy. Open the File menu and select "New Web Site".
You
will
be
presented
with
the
following
dialog:

You need to select "ASP.NET Web Site", if it's not already selected. You should also
name your new site. This is done by entering a name in the Location box. This text
box is probably already filled for you, with the last part being something like
"Website1". You can choose to accept this, as well as the location of the project, or
you can enter a new one, like I did. I have created a folder, "My Websites", and
within this folder, I would like to create the new project with the name of
"FirstWebSite". For now, this is less important, but later on you might wish to gather
all
your
projects
in
a
specific
folder.
This tutorial will focus on the C# language. Once again, no knowledge of this is
required, so if you already know another .NET language, you will get to learn some
C# with this tutorial as well. Select C# in the Language dropdown. Now, click the Ok
button
to
create
this
new
website.
VWD will create a very basic website for you, consisting only of a Default.aspx file

(and it's partner, the Default.aspx.cs file) and an App_Data folder. I will explain this
later, but for now, just accept the fact that they are there.
In almost every programming tutorial you will find the classic "Hello, world!"
example, and who am I to break such a fine tradition? Let me show you how you
can say hello to the world from ASP.NET. Open the Default.aspx (if it's not already
opened) by doubleclicking it in the Solution Explorer. It already contains a bunch
of HTML markup, as well as some stuff you probably won't recognize, like the Page
directive in the top, or the runat attribute on the form tag. This will all be explained
later,
but
for
now,
we
want
to
see
some
working
code.
First of all, we will add a Label control to the page. A Label control is some what
simple, since it's just used to hold a piece of text. Add the following piece of HTMLlooking code somewhere between the set of <form> tags:
<asp:Label runat="server" id="HelloWorldLabel"></asp:Label>

Secondly, add this script block somewhere on the page, preferably below the Page
directive in the top:
<%
HelloWorldLabel.Text = "Hello, world!";
%>

If you haven't worked with ASP.NET before, I'm sure there's a bunch of things that
you're wondering about now, but as I said, this is all about seeing some results right
now. To see the page in action, use Debug -> Start Without Debugging, or simply
press F6. VWD will now compile your project, and launch the page you're working on
in your default browser. The page will simply have a piece of text which says "Hello,
world!" - congratulations, you have just created your first ASP.NET website! Here is
the complete listing:
<%
HelloWorldLabel.Text = "Hello, world!";
%>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
</div>
</form>
</body>
</html>

CodeBehind
While our first example was fine, we unfortunately broke one of the coding principles
of ASP.NET: To separate markup and code. As you noticed, we added a scripting block
(using <% %>), where we wrote a line of C# code to use the label. While this is just
fine for a small and simple example like this, we would soon get a real mess with a
bunch of C# code within an even bigger amount of HTML code. If you throw in some

10

JavaScript and some CSS as well, it will soon become very chaotic to edit. That's why
MS introduced CodeBehind, a technique which allows you to completely separate
markup (HTML, CSS etc.) and code (C#, VB.NET etc.). So let's remove the script
block
(from
<%
to
%>)
and
save
the
file.
As we talked about earlier, VWD added a file called Default.aspx.cs. If you can't see it
in the Solution Explorer, then click the little plus sign left of the Default.aspx file.
Open this file. Now, if you haven't worked with .NET or another non-web
programming language before, it might look a bit scary at this point. It looks nothing
like HTML. However, I will try to explain the different parts of the content, and soon
you will hopefully see that CodeBehind is a great tool to get a better overview of your
work. Here is a complete listing of the file as it looks right now:
using
using
using
using
using
using
using
using
using

System;
System.Data;
System.Configuration;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
}
}

For now, the top part is rather irrelevant to us. It's a list of namespaces being
included with the using keyword, for usage in the file. Since this is an ASP.NET
tutorial and not a dedicated C# tutorial, I won't explain this in depth. Next, we have
the class. Classes are a part of the concept of Object Oriented programming, which
has become very popular, especially with languages like Java and C#. OO is a very
complex subject, which also won't be explained within this tutorial. The name of this
class is "_Default", and the : (colon) tells us that this class inherits from the Page
class in the System.Web.UI namespace. This means that our page can already do a
bunch of things, without any programming, because it inherits methods and
properties from another class. All ASP.NET pages inherits from the Page class, or
another
class
which
inherits
from
the
Page
class.
The only method within this class is the Page_Load, which is called everytime the
page is loaded. Let's use that to our advantage, and set the ext from this method.
We can use the exact same line of code as before, but of course without the script
block tags. Add the line of code between the { and } characters:
HelloWorldLabel.Text = "Hello, world!";

That's it. Run the project (F6), and have a look. The page looks exactly like before,
but we have just used CodeBehind for the first time.
ASP.NET is an event-driven way of making web applications. With PHP and Classic
ASP, you have one file, which is executed line after line, from start to end. However,
ASP.NET is very different. Here we have events, which are either activated by the
user in one way or another. In the previous example, we used the Page_Load
11

method. Actually, this is an event, which the Page class calls when the page is
loaded. We will use the same technique in the next example, where we will add a
couple of controls to our simple hello world example. To make it a bit more
interesting, we will change the "world" word with something defined by the user.
Have a look at this codelisting, where we add two new controls: A Button control and
a TextBox control.
<form id=form1 runat=server>
<div>
<asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
<br /><br />
<asp:TextBox runat="server" id="TextInput" />
<asp:Button runat="server" id="GreetButton" text="Say Hello!" />
</div>
</form>

As you can see, we now have the 2 new controls added, but they really can't do
much at the moment. You can run the example if you wish to check this out for your
self - if you click the button, the page is simply reloaded. Let's change that, and let's
start by doing it the easy way.click the Design button. Now you will see a visual
representation of our page. We wish to add a Click event to the button, and this is
very simply - just doubleclick the GreetButton, and you will be taken to the
CodeBehind file of our page. As you can see, a fine new method has been added,
called GreetButton_Click. If you have a look at the Default.aspx file (you need to go
from Design view to Source view), you will see that an attribute has been added to
our Button control, telling which method to call when the button is clicked. All this
work
done
with
a
simple
doubleclick.
Now lets add some code to our new event. We wish to use the text from the
TextBox, on our good old Label with the "Hello, world!" text. This is also very simple,
and all it requires is a single line of code:
HelloWorldLabel.Text = "Hello, " + TextInput.Text;

Run the project again (F5), and you will see the our old page with a couple of new
controls. The "Hello, world!" text is still there, because we set it in the Page_Load
event. Now try entering a name in the textbox, and press the button. Voila, the text
is changed, and we have just used our first control event. Notice how we can add
code which is not necessarily called unless the user performs a specific task.
Okay, the onclick event from last chapter was easy, but let's try creating all the code
required to use an event from scratch. We will also add yet a new control, to make
things more interesting - the DropDownList, which allows the user to select an item
from a list. Add the folowing code snippet somewhere in the Default.aspx file:
<asp:DropDownList runat="server" id="GreetList" autopostback="true">
<asp:ListItem value="no one">No one</asp:ListItem>
<asp:ListItem value="world">World</asp:ListItem>
<asp:ListItem value="universe">Universe</asp:ListItem>
</asp:DropDownList>

This thing works just like a normal HTML SELECT element, which is of course what
it's translated into upon rendering. The only attribute that would seem new to a
person with basic HTML experience, is the autopostback. You will learn more about

12

postbacks in one of the next chapters, but for now, just know that it makes the
control contact the server eachtime an item is selected by the user. We will use this
to our benefit now, by adding an event:
<asp:DropDownList
runat="server"
id="GreetList"
autopostback="true"
onselectedindexchanged="GreetList_SelectedIndexChanged">

We are using the onselectedindexchanged event, and assigning a method from


CodeBehind which does not yet exist. You are free to choose the name of the
method, but using a convention with the name of the control, an underscore, and
then the name of the event, helps you keep track of it all. We better go create the
event, so change to the Default.aspx.cs file, and add the following method:
protected void GreetList_SelectedIndexChanged(object sender, EventArgs e)

{
HelloWorldLabel.Text = "Hello, " + GreetList.SelectedValue;
}

Once again, we make this extremely simple. We use the SelectedValue property of
our dropdown list, which holds the text from the value property of the selected item.
Try running the site, and select an item from the dropdown list.

13

Chapter 2 The Development Environment


The Integrated Development Environment (IDE) we will be using to build
our ASP.NET 2.0 applications is Visual Web Developer (VWD). Throughout this
chapter we will take a high-level guided tour of the IDE so you become
familiar with most of the important tools available to build your
applications more quickly and with less hassle. As you will see, building web
appli- cations with VWD is no hassle at all.
Although hundreds of pages could be written to encompass all the
productivity tools avail- able in such a powerful development environment,
this chapter will focus on the high-level items you will want to know right
away. A lot of the other wizards and tools available are covered throughout
the book as we discuss the aspects of the technology we are dealing with.
For example, we will discuss the wizards that are used to configure a data
source in the chapters that discuss working with data.
Main Menu and Toolbars:
Microsoft has been relatively consistent over the years in providing a
common look when it comes to the main menu and toolbar options. Visual
Web Developer is no exception, as seen in Figure 2-1. In this section we
cover the main menu and toolbar options and what they do. Of course,
VWD has menu items for Copy, Paste, Delete, and so on. We venture to
assume you know what these do and focus the discussion around
development-oriented commands.

The menu options that you do not see will become available once you
begin a website. For now, lets just create one quickly so you can see the
rest of the menu options. Nav- igate to File New Website under the
main menu. In the New Website dialog, leave all values at their default and
click OK (refer back to Chapter 1 for additional reference to this dialog).
Now that you have created a website, all the other menu options
and toolbars are available to experiment with. Lets start looking at them in
more detail and tap out some code where the various options require it.
File Menu
Underneath the File menu is where you are provided all the options
to do the tasks associated with core file operation. As you just saw, you are
able to create new websites, open existing websites, add new files, and
add existing files to websites. One of the nice features of this menu is the
Recent Files and the Recent Projects items. If you find yourself working on a
lot of files in many websites, these menu items keep a relatively extensive
history of the files and projects you have been working in. Instead of
having to use the Open command and navigate to the file manually, you
may more easily find it in these lists and open it directly from there.
Edit Menu
Underneath the Edit menu you will find the most common text
editing options, such as Copy and Paste. In addition, you have the Undo
(one of our favorites) and Redo operations, which allow you to undo the
last item(s) that you did or redo, which you can do after an undo. We have
not tested exactly how many operations the Undo/Redo keeps in memory,

14

but we have yet to be unable to recover from our worst situations.


View Menu
The View menu is another one of the standard menu options that we
see in all Microsoft appli- cations. This menu has all the commands that
will allow you to get at the majority of the panes you see along the sides
and bottom of the IDE, such as the Solution Explorer and the Properties
pane. If you ever accidentally close one of them, you can come here to
open it again. We will be covering the majority of the panes available in
more detail later in the chapter. In addition, the View menu contains a list
of all the available toolbars that you can show. For the most part, the
toolbars encapsulate common themes of functionality that are typically
also available through the standard menu options. The toolbars do provide
easier access if there are commands you do more often.
Website Menu
The Website menu provides the commands that perform operations
on the solution. The solu- tion is a container for one or more projects. This
means that you can, if you have multiple websites, hold them all within
one solution and have them all available at the same time. This menu is
sensitive to what is available in the Solution Explorer window. For example,
certain items will show and hide based on whether or not there are
multiple projects. To see these other items, repeat the steps you
performed earlier, except instead of selecting File New Website, select
File Add New Website. Now with two websites in the solution, you will
see some additional options in the Website menu.
In the Website menu, you now have the ability to add new and
existing files to websites. You will also be able to add References. Adding
References is required when you need to use code provided to you in
external assemblies. Assemblies are generated when .NET code is compiled.
These are dynamic link libraries (DLLs). You can also add Web References if
there are web services you would like to use in your project. When there
are multiple projects in the Solution Explorer, you are also provided with
the Project Dependency and Project Build Order options. These allow you
to specify if any of the projects are dependent on one another. The build
order is very important. If one project is referencing the output from
another project, you had better be sure the output from the other project
exists first. In turn, the IDE will ensure that they are compiled in the
proper order.
.
Build and Debug Menus
The Build menu provides you with options for compiling your website.
When compiling, you convert all of your code into a format known as
machine language so the computer under- stands the instructions it
receives from your code. In .NET this is a two-part process. When your
assemblies are first compiled, they are compiled into Intermediary
Language (IL). Then, when the code is actually required to run, the .NET
runtime compiles the IL into machine lan- guage. This is called Just-InTime (JIT) compilation.
There are a variety of compiling options for ASP.NET applications that
we examine a little later. For instance, after typing out a lot of new code,
you may want to do a quick check to ensure there are not any compile
errors. By selecting the Build Solution option under the Build menu, you will
quickly receive feedback about build errors. This is also a menu where you

15

will add and remove items depending on what you select in Solution
Explorer. If you have the project node selected in the Solution Explorer, you
will see options pertaining only to building solutions. However, if you select
one ore more files within a project, you can also use the Build Page option.
This option is convenient in cases where multiple pages may be causing
compile errors and you want to be able to fix things up one page at a time.
The Debug menu provides commands necessary to run your
application, including both the Start (F5) and the Start without Debugging
(Ctrl+F5) commands.
Tools Menu
The Tools menu contains a few interesting items. From the Tools
menu, you have the ability to customize the Toolbox. The Toolbox is a side
pane that contains all the controls you have avail- able to place on a web
page. The Toolbox is one of the most important areas when building Web
applications. We reserve our main discussion on this topic for a later
section dedicated to the Toolbox. In addition to the Toolbox, the Tools
menu contains the command to launch the Add-In Manager, where you
can load environment add-ins. There are always a large number of tools
available out there, known as third-party tools, that can do things that
perhaps the product team at Microsoft did not think of or that someone
just finds useful. You can install these add-ins and use this menu option to
load the add-in into the environment to make it available for use.
The Tools menu also provides the Options command. The Options
dialog is covered in great detail later. In essence, this dialog provides you
the ability to configure everything to do with your development
environment, from how you would like your HTML displayed to the color you
would like the keywords in your code to appear. It truly is the one-stop
shop for customizing your development experience. The last command to
note here is the Customize button, which allows you to customize the
organization of your toolbars and the functionality they provide.
Customize Your Toolbars
Under the Tools menu you have the ability to customize all of the
menus and toolbars we have looked at so far. Essentially, every menu item
we have described in the main menu bar can also be configured to be
displayed on a toolbar. A slew of toolbars provided out of the box are available from below the View menu. If a toolbar and a command that you want
to appear on that toolbar is not present, you can add it by going into Tools
Customize. You may navigate around in this dialog, and when you see a
command you want, simply drag it onto the toolbar.
Window Menu
The Window menu is also one of the Microsoft standard menu items.
In the case of the devel- opment environment, it does have a few useful
items worth mentioning. One of the first buttons you will notice is the Split
command. This is useful when working with larger code files. You can split
the file into two so that you can see code at different areas of the file.
Help Menu
The Help documentation shipped with VWD can be very helpful. The
Microsoft .NET Frame- work is just too large for any one person to master
completely. As such, the Help files are a valuable resource. In this section
we take a look at the documentation at the disposal of the developer.

16

Contents and Index:


The Contents and Index are the typical Help file format that you are
probably used to from
most other applications. If you have ever seen the Help files from other
applications that are in the format of .chm files or even some HTML help
system, there are two tabs. One tab provides
a high-level table of contents that you can drill through, and the other tab
provides an index just like the index in the back of a book. The index
provides an alphabetical listing of all the key- words available in Help.
Dynamic Help:
In addition to the standard contents and index help options, VWD
offers Dynamic Help. This is a dockable side pane that will dynamically
reload itself with the topics that pertain to the cur- rent selection. Lets use
the website you built in Chapter 1 to demonstrate this. Open the code file
for the SignUpApproved.aspx Web Form. In the code that we entered,
highlight some of the keywords, such as FindControl and TextBox. Take a
look at Figure 2-5 to see what happens when we select the PreviousPage
property. The Dynamic Help is updated to reflect the selec- tion. If we want
to get help on the PreviousPage property, we can simply click the link
provided in the Dynamic Help window pane and we will be brought to the
documentation for the property. This can be a huge time-saver over trying
to use the Help index and Help search engine.
Dockable Windows:
One of the key features of an effective development environment is
easy access to common tasks. We saw this with the toolbars and menu
structure. In addition to that, there is also a wide range of dockable side
and bottom window panes. It is the fact that each and every window is
dockable that makes these little panes so useful. This lets you place each
window in an area of the IDE that fits most comfortably for you. To move a
window around, you simply left-click the title bar and drag it to its new
location. Once you begin to drag the window, the IDE will provide you with
some icons to assist in the operation.
As you drag a window around the IDE, you will notice a larger image
with four arrows and a centerpiece that follows you around. Actually, this
graphic will be centered over any other window where you are currently
hovering. If you move the cursor right to the center of this while dragging a
window, you will group this window with the one where you are currently
hovering.

17

Dragging and dropping a dockable window


If you so choose, you may also convert any dockable window into a
tabbed document. Tabbed document is the term used to describe any
window that is open in the middle of the IDE. For example, when you
double-click a code file in the Solution Explorer, it opens up in the middle of
the IDE as a tabbed document. To try this, right-click the title bar of any
dockable window and select Tabbed Document. To make the window
dockable again, simply right-click and select Dockable. At this point, we will
leave you to experiment with this.
Next, well take a thorough look at all the windows available within
the IDE to understand the important role that each will play in our
development. Well begin with one of the most important windows, the
Solution Explorer.
Solution Explorer:
In this view of my Solution Explorer, we can see a website project. It
is displayed as the path on the file system to where the website is located.

The Solution Explorer is the window where you will be able to see the
structure of your proj- ects. In this view, you will be able to see every file
and folder that you have included with every project that is currently open.
You will have the ability to add new files, delete existing files, rename files,
add new projects, and so on. We will take a look at all the features
provided by this window. By default, this window is located closer to the top
on the right-hand side.

18

The Solution Explorer does provide some shortcuts to some of the options
we discussed earlier in the section on the Website menu. Place your cursor
on one of the Website nodes in the Solution Explorer and right-click. You will
be provided with a context menu that encapsulates all the functionality we
saw on the Website menu, plus one more option called Property Pages. If
you select this option you will see a dialog that allows you to configure
aspects of the Website projects properties. There are additional options
available depending on the type of item you right-click in the Solution
Explorer. For instance, if you right-click Default.aspx, you are again presented
with a context menu. This time, the menu contains all of the standard file
operations such as Copy and Delete. However, you also have options to
view this file in different ways. This is because the IDE is smart enough to
know that you have selected a web page. As a result, it provides you the
options to view the file at design time in various modes such as Design
View or Code View; it also gives you the ability to view in the browser, in
which case the page will be launched in your default browser or you can
specify a different browser by selecting the Browse With option. There is
also a toolbar across the top of the Solution Explorer window that provides
shortcut buttons to some of the operations we have discussed and is
context sensitive to what you select in the TreeView.
Now that you are familiar with the Solution Explorer, we can look at the
next very important docking window, the Toolbox.
Special Folders:
Within Solution Explorer, by default, you will see a data folder. You
will also notice that this folder has a different icon in the TreeView
than regular folders. There are a handful of folders that have
special names and if included in your project will have special
meaning to your application.
Folder Name
App_Assemblies

Description
This folder contains all output assemblies and
assembly references that your website project
depends on.
App_Code
The runtime checks this folder for any code files. If
any are found, it automatically makes them
available to your applications and compiles them
at runtime.
App_WebReferences This folder contains all the web service references
that the website is currently referencing.
App_Data
This folder contains files such as SQL Server
database files or XML data.
App_Browsers
App_GlobalRes
ources
App_LocalReso
urces
App_Themes

This folder contains browser definition


files.
This folder provides a container for resources that are
global to the application.
This folder contains the resources used to
display text in the different locals for
individual Web Forms.
This folder contains theme files that permit applying a
common look across an entire website.

Toolbox:

19

The Toolbox is the pane that contains all the controls the IDE knows
about that you can use to build web pages. If you want to add a textbox,
label, WebParts, login controls, or data controls, they are all grouped here
in the Toolbox, as shown in this Figure.
The Toolbox automatically has items grouped
into their logical sections. Only controls/
components that pertain to the currently open
document will be shown here. So, if you do not
have a Web Form open, you will not see items in
the Toolbox that pertain only to Web Forms.
Table 2-2 lists the various groupings that are
available out of the box.

The Toolbox Organization


Grouping
Standard
Data

Navigatio
n

Validation

Login
WebParts

HTML
General

Description
All standard ASP.NET server controls, such as textboxes, buttons,
check boxes, wiz- ards, and the Calendar, are listed here.
This section lists the controls that are used for connecting to
data sources. This sec- tion also contains the powerful gridbased controls for displaying data, such as the GridView and the
Repeater.
This section contains the controls that perform the common
tasks related to site navigation, such as the Menu and
SiteMapPath.
This section contains the validation controls. These controls are
used to provide both client- and server-side validation of a users
input. Examples are the Required- FieldValidator and the
CompareValidator.
This section contains the components necessary to build an
authentication system into your Website, including the Login,
LoginStatus, and LoginView controls.
This section contains the necessary controls to build a userdriven dynamic web- site using the Personalization providers.
These controls include the WebPartManager, WebPartZone, and
the various types of WebParts.
This section contains all the standard HTML controls, such as the
plain HTML Input controls.
This section contains any other items that you may add
manually or that may not fit into any other logical group. By
default, this section contains the pointer, which switches the
context of the mouse cursor to the pointer for object selection.

Properties Window:
The Microsoft .NET Framework is an object-oriented development
platform. As such, it con- sists of many classes, each of which contains
properties. This, of course, includes the controls you will be placing on Web
Forms. The Properties window, as shown in Figure 2-11, is an area where
you can configure the controls you use without typing any code. The IDE
will take care of placing the appropriate code in the appropriate place.

20

The Properties window for a new button on a Web Form

When you first drag and drop a button from the Toolbox onto the Web
Form and then switch to source view, you see that the HTML the IDE
rendered looks something like this:
<asp:Button ID="Button1" Runat="server" Text="Button" />
Using the Properties window, change the name to MyButton, change
the text to My.Button, and change the BorderColor to some other color. Now
look at the source. It should look similar to this (depending on what color
you chose):
<asp:Button
ID="MyButton"
Runat="server"
Text="My
Button"
BorderColor="Red" />
All these values have been set by using the convenience of the
Properties window; you did not have to type any code.
There are a couple of ways to make a controls properties available in
the Properties window. The first is to select the control on the designer,
and the Properties window will auto- matically change to the selected
control. The second is to place the cursor within a controls HTML source in
the source view; again, the Properties window will automatically change to
the selected control. Finally, you can manually find your control by name in
the drop-down list provided within the Properties window itself. By
changing the selection in the list, you inherently change the control whose
properties the Properties window will be displaying.
The Properties window also has a little toolbar at the top that gives
you the ability to configure how you would like to display the properties.
The default is for the properties to be displayed in groups as you saw in
Figure. However, by clicking the A-Z icon, you tell the Properties window to
display its items in alphabetical order. The Properties window also provides a way to configure events for your controls. For example, if a user of
your web page clicks a button, you may want to execute code based on the
button clicked. By clicking the lightning bolt icon, you switch the window to
display the events available to the currently selected control, and again,
you may have these listed alphabetically or grouped by categories.
Database Explorer:
The majority of web applications are driven by data in one way or another.
The Database Explorer provides a nice, easy way to configure connections
to various data sources and create new SQL Server databases.

21

Output Window:
Once our application is in a state where we are able to start compiling it,
the Output window becomes very useful.

The Build view provides information about errors, warnings, successes, and
failures for each project and/or file that you selected during the last
compilation. The Debug view shows much lower-level information about
the last compilation. In this view you can see what files the runtime has
loaded to complete the compilation. The Refactor view shows information
about any code refactoring you have done recently. For example, in the
earlier example when you renamed Button1 to MyButton, an entry was
shown on the Refactor view in the Output window.
Error List:
The Error List windows name is very self-descriptive. Any errors that exist in
the current open documents are displayed here. The IDE is constantly
scanning the open documents for errors. For example, say the following is
typed into the code for Default.aspx:
Public Partial Class Default_aspx myInt
End Class
This code is obviously an error and will appear as an error in the
Error List as shown in below. If you double-click on the item in the list, you
will be brought directly to the proximity, if not the exact line, that is
offending, so you can make any necessary corrections. As soon as you
prefix that garble with a data type, such as int, and add a semicolon to the
end, the Error List clears dynamically because the runtime now views that
line as a legitimate variable declaration at the class level.

The toolbar at the top of this window shows three toggle buttons. If
you are working in a large project, the number of messages shown in this
list could get large. The Error, Warning, and Messages buttons toggle the
visibility of the messages that fall into each respective category. You can
also right-click the Error List and choose columns to be displayed and the
sort order for the listed items. You can also change the column order by
dragging and dropping the columns.

22

Task List:
The Task List window, shown in Figure below, provides a list of userdefined tasks you can createas well as items based on comments created
throughout your code that begin with the appropriate token. The dropdown list at the top of the window lets you filter the list based on these two
types of tasks. Note that the Comments view only appears if there are
actually any comments defined using a valid token.

If you begin a comment line with a valid token that the IDE
recognizes as a Task List com- ment, such as the word TODO, it will be
picked up and displayed by the Task List. At any time, you can double-click
an item in the Task List and be brought directly to that line of code and
complete any necessary work. Using the previous example from the Error
List, if you determine that now is not a good time to fix that error, perhaps
because of the amount of work involved, you could simply comment on the
line of code so your website would compile and mark it with a TODO
comment and you do not forget about it.
Find Results View:
The Find Results View displays the results of Find operations. Under
the menu Edit Find and Replace are a variety of Find options that can
be very useful when looking for specific items throughout your solution.
Most of these options are self-explanatory. However, we will add that there
is a second Find Results View that is available when performing many
searches. You can specify that the results of your search be displayed in
either Find Results 1 or Find Results 2. This gives you some flexibility so you
do not wipe out previous searches in case you still need that information.
Class View:
The Class View window, available from View Other Windows
Class View, provides a mini object browser for your websites. You can use
this view to traverse your own class hierarchy and view the organization of
your code. In Class View, classes are called symbols.

The Class View is handy in that you can drill through to find particular
symbols, and once you find them, you can right-click and be brought to
their definition. This will open the document containing the symbol itself so
you can further examine its details. This view is especially useful for viewing
your object hierarchy. Some classes may have specific interfaces
implemented that you may be interested in knowing about, such as when
working with various types of collection classes.

23

Chapter 3 Server Controls


All of the controls have a very specific function to accomplish. Every control
consists of an individual class that allows you to extend the class or even
develop your own class or custom control. The functionality of the different
controls comes in the form of displaying data or information, navigation,
security, and validation. Throughout this chapter, we will discuss many of
the main server controls and show how to use them within web
applications. Many times within a development project, there will be an
instance where none of the included server controls meets the needs of
your requirements. In such cases, you also have the ability to create your
own custom server controls, thus giving you the flexibility you need.
Like HTML server controls, Web server controls are also created on the server and
they require a runat="server" attribute to work.
Label Control:
The Label control is used to display text on a page. The text is programmable.
Note: This control lets you apply styles to its content!
Properties
Property

Description

runat

Specifies that the control is a server control. Must be set to "server"

Text

The text to display in the label

Example : Display Message on Label on page load.


public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Welcomt to first Asp.net Webpage!!!";
}
}
Button Control :
The Button control is used to display a push button. The push button may be a submit button or a
command button. By default, this control is a submit button. A submit button does not have a
command name and it posts the Web page back to the server when it is clicked. It is possible to write
an event handler to control the actions performed when the submit button is clicked.
A command button has a command name and allows you to create multiple Button controls on a
page. It is possible to write an event handler to control the actions performed when the command
button is clicked.
Properties
Property

Description

24

CausesValidation

Specifies if a page is validated when a Button control is clicked


The CausesValidation property specifies if a page is validated when a Button
control is clicked.
Page validation is performed when a button is clicked by default.
This property is mostly used to prevent validation when a cancel or reset
button is clicked.

CommandArgumen Additional information about the command to perform.


t
CommandName

The command associated with the Command event.

OnClientClick

The name of the function to be executed when the button is clicked.


The OnClientClick property is used to sets a client side script to be run when
the Button control is clicked.
The script specified in this property is run by the Button's event "OnClick" in
addition to the predefined script.

PostBackUrl

The URL of the page to post to from the current page when the Button
control is clicked
The PostBackUrl property is used to gets or sets the URL of the page to
post when the Button control is clicked.

Text

The text on the button


The Text property is used to set or return the text on a button control.

ValidationGroup

The group of controls for which the Button control causes validation when it
posts back to the server
The ValidationGroup property specifies which group of control is validated
on validation.
This property is mostly used when there are several buttons in a form.
Example : Display message when user clicks on submit button.
protected void BtnSubmit_Click(object sender, EventArgs e)
{
Response.Write("Welcome User.");
}
Output :

HyperLink Control:
The HyperLink Web server control provides a means of creating and manipulating
links on a Web page from server code. Use the HyperLink control if you want to link
to another Web page when the control is clicked.
Property

Description

ImageUrl

The URL of the image to display for the link


The ImageUrl property is used to set or return the URL of
an image to display for the hyperlink.

25

NavigateUrl

The target URL of the link


The NavigateURL property is used to set or return the URL
of a HyperLink control.

Text

The text to display for the link


The Text property is used to set or return the text of a
HyperLink control.

Example :
Design Source:
<asp:HyperLink ForeColor="#FF9933" ID="HyperLink1" runat="server"
NavigateUrl="~/how-to-use-textbox.aspx">Display TextBox File
</asp:HyperLink>

LinkButton Control:
The LinkButton control is used to create a hyperlink button. Note: This control looks
like a HyperLink control but has the same functionality as the Button control.

Property

Description

PostBackUrl

The URL of the page to post to from the current page when the LinkButton
control is clicked

Text

The text on the LinkButton

ValidationGroup

The group of controls for which the LinkButton control causes validation
when it posts back to the server

Example:
Use the LinkButton control if you want to link to another Web page when the control
is clicked.
Design Source:
<asp:LinkButton ID="LinkButton1" runat="server"
PostBackUrl="~/how-to-use-textbox.aspx"> Display TextBox File
</asp:LinkButton>

26

TextBox Control:
The TextBox control is used to create a text box where the user can input text.
Properties
Property

Description

AutoPostBack

A Boolean value that specifies whether the control is


automatically posted back to the server when the contents
change or not. Default is false.
The AutoPostBack property is used to set or return whether or
not an automatic post back occurs when the user presses
"ENTER" or "TAB" in the TextBox control.
If this property is set to TRUE the automatic post back is
enabled, otherwise FALSE. Default is FALSE.

MaxLength

The maximum number of characters allowed in the textbox


The MaxLength property is used to set or return the maximum
number of characters allowed in a TextBox control.

ReadOnly

Specifies whether or not the text in the text box can be changed
The ReadOnly property is used to set or return whether or not
the text in the TextBox control can be changed.
If this property is set to TRUE the text can not be changed,
otherwise FALSE. Default is FALSE.

Text

The contents of the textbox


The Text property is used to set or return the text of a TextBox
control.

TextMode

Specifies the behavior mode of a TextBox control (SingleLine,


MultiLine or Password)
The TextMode property is used to set or return the behavior
mode of a TextBox control.
Attribute

Description

mode

A number specifying the maximum number of


characters allowed in the text box
Possible values:
SingleLine - Default. One line text box
MultiLine - Text box with multiple lines
Password - One line text box that masks
the input

27

ValidationGroup

The group of controls that is validated when a Postback occurs

Wrap

A Boolean value that indicates whether the contents of the


textbox should wrap or not.
The Wrap property is used to set or return whether or not the
text content wraps within a multiline text box.
This property can only be used if TextMode="Multiline"

ASP Source:

<html>
<body>
<form runat="server">
A basic TextBox:
<asp:TextBox id="tb1" runat="server" />
<br /><br />
A password TextBox:
<asp:TextBox id="tb2" TextMode="password" runat="server" />
<br /><br />
A TextBox with text:
<asp:TextBox id="tb3" Text="Hello World!" runat="server" />
<br /><br />
A multiline TextBox:
<asp:TextBox id="tb4" TextMode="multiline" runat="server" />
<br /><br />
A TextBox with height:
<asp:TextBox id="tb5" rows="5" TextMode="multiline" runat="server" />
<br /><br />
A TextBox with width:
<asp:TextBox id="tb6" columns="30" runat="server" />
</form>
</body>
</html>

28

Example :
Design View:

Aspx Code :
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Welcome to Asp.net");
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblResult.Text = "Welcome " + txtUserName.Text;
}
protected void btnClear_Click(object sender, EventArgs e)
{
txtUserName.Text = "";
}
}
Output :

29

CheckBox Control :
The CheckBox control is used to display a check box. Check boxes are used when you want to let the
visitor select one or more options from a set of alternatives. If only one option is to be selected at a
time you should use radio buttons instead.
Property

Description

AutoPostBack

Specifies whether the form should be posted immediately after the Checked
property has changed or not. Default is false

CausesValidation

Specifies if a page is validated when a Button control is clicked

Checked

Specifies whether the check box is checked or not


The Checked property specifies whether or not a CheckBox control is
checked.
By default a checkbox is not checked.

InputAttributes

Attribute names and values used for the Input element for the CheckBox
control

LabelAttributes

Attribute names and values used for the Label element for the CheckBox
control

Text

The text next to the check box


The Text property is used to set or return the text of a CheckBox control.

TextAlign

On which side of the check box the text should appear (right or left)
The TextAlign property is used to set or return the alignment of a checkbox
text.
Default alignment is "right"

ValidationGroup

Group of controls for which the Checkbox control causes validation when it
posts back to the server

OnCheckedChange The name of the function to be executed when the Checked property has
d
changed

Example: Display selected softwares which user wants in a label when page is
submitted.

30

Code :
protected void BtnSubmit_Click(object sender, EventArgs e)
{
Label1.Text = "you have select software to instail;<br>";
if (CheckBox1.Checked == true)
{
Label1.Text += CheckBox1.Text + "<br>";
}
if (CheckBox2.Checked == true)
{
Label1.Text += CheckBox2.Text + "<br>";
}
if (CheckBox3.Checked == true)
{
Label1.Text += CheckBox3.Text + "<br>";
}
if (CheckBox4.Checked == true)
{
Label1.Text += CheckBox4.Text + "<br>";
}
if (CheckBox5.Checked == true)
{
Label1.Text += CheckBox5.Text + "<br>";
}
if (CheckBox6.Checked == true)
{
Label1.Text += CheckBox6.Text + "<br>";
}
}

Output :

31

Example 2: Display shipping details as billing details if the checkbox is checked.


Note : set AutoPostBack property of checkbox to True.

RadioButton Control:
The RadioButton control is used to display a radio button.
Tip: To create a set of radio buttons using data binding, use the RadioButtonList control!
Properties
Property

Description

AutoPostBack A Boolean value that specifies whether the form should be posted immediately
after the Checked property has changed or not. Default is false
Checked

A Boolean value that specifies whether the radio button is checked or not

GroupName

The name of the group to which this radio button belongs

Text

The text next to the radio button

TextAlign

On which side of the radio button the text should appear (right or left)

Example: Display selected gender on label when page is submitted.

Code:
protected void Button1_Click(object sender, EventArgs e)
{
if (rbtMale.Checked == true)
Label1.Text = rbtMale.Text;
else
Label1.Text = rbtFemale.Text;
}

Example: Display 3 products with rate using checkbox. Write code to calculate Bill
amount as whichever products user wants to purchase. Calculate tax and display
amount to pay. Display mode of payment (Cheque, Cash or Credit Card) on label
when page is submitted.

32

Checkbox List Control:


The CheckBoxList control is used to create a multi-selection check box group.
Each selectable item in a CheckBoxList control is defined by a ListItem element!
Tip: This control supports data binding!
The CheckBoxList control raises a SelectedIndexChanged event when users select
any check box in the list. By default, the event does not cause the form to be posted
to the server, although you can specify this option by setting the AutoPostBack
property to true.
Example: In this example we declare one CheckBoxList control, and one Label
control in an .aspx file. Then we create an event handler for the
SelectedIndexChanged event which displays some text and the selected item, in a
Label control.
Design:

Code:
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = ("Your speak the following language(s): " + CheckBoxList1.Text);
}
RadioButtonList control:
The RadioButton and RadioButtonList Web server controls allow users to select one item from a
predefined list. The following topics provide information that you will find useful in learning to work
with these two controls.
Example: In this example we declare one RadioButtonList control, and one Label control in an
.aspx file. Then we create an event handler for the SelectedIndexChanged event which displays
some text and the selected item, in a Label control.
Design :

33

Code:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = "Your level of education is " + RadioButtonList1.Text;
}
Image Control:
The Image Web server control enable you to display images on a Web Forms page
and manage the images in server code. You can specify the graphics file for an
Image control at design time or at run time programmatically. You can also bind the
control's ImageUrl property to a data source to display graphics. Unlike most other
Web server controls, the Image control does not support any events. For example,
the Image control does not respond to mouse clicks. Instead, you can create an
interactive image by using the ImageMap or the ImageButton Web server controls.
Example:
Design:
Output:

Code:
protected void Page_Load(object sender, EventArgs e)
{
Image2.ImageUrl = "~/images/aspbook2.jpg";
}

34

ImageButton Control:
The ImageButton control is used to display a clickable image. In the following example
we declare one ImageButton control in an .aspx file.
Example:
Use the ImageButton control if you want to Display Text on Web page when the control is clicked.
Design:

Code:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Response.Write("Visual Web Developer 2008 Express Edition.");
}
ImageMap Control:
ImageMap control. This control enables you to create an image that has individual
regions that users can click; these regions are referred to as hot spots. Each of
these hot spots can be a separate hyperlink or can raise a postback event.
The following are some useful property.
1. ImageUrl: Url of the Image.
2. AlternetText: Appears if image not loaded properly.
3. HotSpotMode: It has three values PostBack, Navigate and Inactive.
The following image shows how can I add CircleHotSpot with ImageMap.

DropdownList Control:
The DropDownList Web server control enables users to select from a single-selection
drop-down list box. The DropDownList control is similar to the ListBox Web server

35

control. It differs in that it shows only the selected item in a box, along with a dropdown button. When users click the button, a list of items is displayed. In addition,
the DropDownList control differs from the ListBox control in that it does not support
multi-selection mode.
Example: Accept two numbers from user and calculate addition, subtraction,
multiplication and division as user select it from dropdownlist control.
Design:

Code:
protected void drp1_SelectedIndexChanged(object sender, EventArgs e)
{
double firstno = Convert.ToDouble(txt1.Text);
double secondno = Convert.ToDouble(txt2.Text);
if(drp1.SelectedIndex == 1)
{
double add = firstno + secondno;
label1.Text = "Addition is :" + add;
}
if (drp1.SelectedIndex == 2)
{
double sub = firstno - secondno;
label1.Text = "Subtraction is :" + sub;
}

36

if (drp1.SelectedIndex == 3)
{
double mul = firstno * secondno;
label1.Text = "Multiplication is :" + mul;
}
if (drp1.SelectedIndex == 4)
{
double div = firstno / secondno;
label1.Text = "Division is :" + div;
}
}
Note: Set Autopostback property of dropdownlist to True.
Output :

Exercise: Display colour of eye which user select from dropdownlist control.
ListBox Control:
The ListBox Web server control allows users to select one or more items from a
predefined list.
To add item at runtime in the listbox control : ListBox1.Items.Add(TextBox1.Text);
To add item at runtime in the listbox control :
ListBox1.Items.Remove(ListBox1.SelectedItem);
Example: Display the message as user select language from the listbox control.
Design:

Code:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{

37

if(ListBox1.SelectedIndex == 0)
{
Label1.Text = " This is HTML. ";
}
if (ListBox1.SelectedIndex == 1)
{
Label1.Text = " This is JAVA. ";
}
if (ListBox1.SelectedIndex == 2)
{
Label1.Text = " This is SERVLET. ";
}
if (ListBox1.SelectedIndex == 3)
{
Label1.Text = " This is PHP. ";
}
if (ListBox1.SelectedIndex == 4)
{
Label1.Text = " This is FLEX4. ";
}
}
Exercise: Change the background colour of the label as user selects a colour from
list box. (Hint: Label1.BackColor=System.Drawing.Color.Yellow;)
Table Control:
The Table Web server control creates a general-purpose table on an ASP.NET Web
page. Rows in the table are created as TableRow Web server controls, and cells
within each row are implemented as TableCell Web server controls.
Property

Description

BackImageUrl

A URL to an image to use as an background for the table


The BackImageUrl property is used to set or return the URL of an image to
use as background image for the Table Control.

Caption

The caption of the table


The Caption property is used to get or set a text that is shown as a caption
for the Table Control.

CaptionAlign

The alignment of the caption text


The CaptionAlign property is used to get or set the alignment of the caption
text for a table.

HorizontalAlign The horizontal alignment of the table in the page

38

The HorizontalAlign property is used to set or return horizontal alignment of


the content in the Table control.
Rows

A collection of rows in the Table

Bulleted List Control:


The BulletedList Web server control lets you create an unordered or ordered
(numbered) list of items, which renders as an HTML ul or ol element, respectively. To
specify the individual list items in the list, you put a ListItem control for each list
entry between the opening and closing tags of the BulletedList control.
Example: In this example we declare one BulletedList control, and one DropDownList
control in an .aspx file. Then we create an event handler for the
SelectedIndexChanged event which displays Bullet Style in a BulletedList control.
Design:
DropdownList Items:
Numbered
Circle
Square
LowerRoman
UpperAlpha
UpperRoman
AutoPostBack : True

Code:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if ((DropDownList1.Text == "Numbered"))
{
BulletedList1.BulletStyle = BulletStyle.Numbered;
}
else if ((DropDownList1.Text == "Circle"))
{
BulletedList1.BulletStyle = BulletStyle.Circle;
}
else if ((DropDownList1.Text == "Square"))
{
BulletedList1.BulletStyle = BulletStyle.Square;
}
else if ((DropDownList1.Text == "LowerRoman"))
{
BulletedList1.BulletStyle = BulletStyle.LowerRoman;

39

}
else if ((DropDownList1.Text == "UpperAlpha"))
{
BulletedList1.BulletStyle = BulletStyle.UpperAlpha;
}
else if ((DropDownList1.Text == "UpperRoman"))
{
BulletedList1.BulletStyle = BulletStyle.UpperRoman;
}
}
AdRotator Control:
The topics in this section provide information about the ASP.NET AdRotator Web
server control, which cycles through a series of clickable banner ads that you define.
The AdRotator control presents ad images that, when clicked, navigate to a new Web
location. Each time the page is loaded into the browser, an ad is randomly selected
from a predefined list.This control uses an XML file to store the ad information. The
XML file must begin and end with an <Advertisements> tag. Inside the
<Advertisements> tag there may be several <Ad> tags which defines each ad.
The predefined elements inside the <Ad> tag are listed below:

Element

Description

<ImageUrl>

Optional. The path to the image file

<NavigateUrl>

Optional. The URL to link to if the user clicks the ad

<AlternateText
>

Optional. An alternate text for the image

<Keyword>

Optional. A category for the ad

<Impressions> Optional. The display rates in percent of the hits


Property

Description

AdvertisementFile The path to the XML file that contains ad information


The AdvertisementFile property is used to set or return the
path to the XML file that contains the advertisement data.
AlternateTextFiel A data field to use instead of the Alt text for an advertisement
d
ImageUrlField

A data field to use instead of the ImageURL attribute for an


advertisement

KeywordFilter

A filter to limit ads after categories

NavigateUrlField

A data field to use instead of the NavigateUrl attribute for an


advertisement
The Target property is used to set or return where to open
the advertisement URL.

40

XML File Code:


Examples:
- <Advertisements>
- <Ad>
<ImageUrl>/banners/test.gif</ImageUrl>
<NavigateUrl>~/Default2.aspx</NavigateUrl>
<AlternateText>Test Site</AlternateText>
<Impressions>50</Impressions>
<Keyword>Test</Keyword>
</Ad>
- <Ad>
<ImageUrl>/banners/sunset.jpg</ImageUrl>
<NavigateUrl>http://www.sunset.com/default.aspx</NavigateUrl>
<AlternateText> Sunset Website</AlternateText>
<Impressions>50</Impressions>
<Keyword>Sunset</Keyword>
</Ad>
</Advertisements>
FileUpload Control:
The FileUpLoad control enables you to upload file to the server. It displays a text box
control and a browse button that allow users to select a file to upload to the server.
When you click on Browse button a popup window will open in which you can select
the file and click open. After that the path of this file will be shown in TextBox. now
click on upload button the file will be uploaded in existing location.
Example :

Coding:
protected void Button1_Click(object sender, EventArgs e)
{
string CurrentFileName;
string ExtFile;
CurrentFileName = FileUpload1.FileName;
ExtFile = Path.GetExtension(CurrentFileName);
if (ExtFile != ".jpg")
{
Response.Write("Only Jpeg Files are suported !!!");
return;
}
if (FileUpload1.PostedFile.ContentLength > 131072)
{

41

Response.Write("The size of big too file , the size of the file must 128 KB not
exceed!!! ");
return;
}
string CurrentPath = Server.MapPath("~/Uploads/");
if (FileUpload1.HasFile)
{
CurrentPath += CurrentFileName;
FileUpload1.SaveAs(CurrentPath);
Response.Write( File uploaded sucessfully !!!");
}
else
{
Response.Write("Can not upload the file !");
}
}
}
Wizard:
This sample demonstrates a basic Wizard control that collects a single piece of
information on the first WizardStep and displays that information to the user on the
Complete WizardStep for confirmation. Instead of displaying this information to the
user, you could write the information to a database or other collection store.
Design:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="how-to-use-Wizardc.aspx.cs" Inherits="how_to_use_Wizard_c" %>
<!DOCTYPE
html
PUBLIC
"-//W3C//DTD
XHTML
1.0
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Transitional//EN"

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to Use Wizard</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Wizard ID="Wizard1" runat="server" Width="472px" ActiveStepIndex="2" >
<WizardSteps>
<asp:WizardStep ID="WizardStep1" runat="server" Title="Data Individual
Questionnaire">
First Name :<br />
<asp:TextBox ID="txtFirstName" runat="server" Width="184px"> </asp:TextBox>
<br />
Last Name :<br />
<asp:TextBox ID="txtLastName" runat="server" Width="176px"></asp:TextBox>

42

<br />
Enter your e-mail :<br />
<asp:TextBox ID="txtEmail" runat="server" Width="184px"></asp:TextBox>
</asp:WizardStep>
<asp:WizardStep ID="WizardStep2" runat="server" Title="Questions About You">
are you want to amemrof with us yes or not?<br />
<asp:RadioButton ID="RadioButton1" runat="server" Text="Yes"
GroupName="Member" />
<asp:RadioButton ID="RadioButton2" runat="server" Text="No"
GroupName="Member" />
</asp:WizardStep>
<asp:WizardStep ID="WizardStep3" runat="server" Title="Membership
Registration">
Confirm your Password:<br />
<asp:TextBox ID="txtMember" runat="server" TextMode="Password"
Width="192px"></asp:TextBox>
</asp:WizardStep>
<asp:WizardStep ID="WizardStep4" runat="server" StepType="Complete"
Title="Data Haded Picked Already" OnActivate="WizardStep4_Activate">
<asp:Label ID="lblOutput" runat="server"></asp:Label>
</asp:WizardStep>
</WizardSteps>
</asp:Wizard>
</div>
</form>
</body>
</html>
Coding:
protected void Wizard1_NextButtonClick(object sender,
System.Web.UI.WebControls.WizardNavigationEventArgs e)
{
if ((e.NextStepIndex == 2))
{
if ((RadioButton1.Checked == true))
{
Wizard1.ActiveStepIndex = 2;
}
else
{
Wizard1.ActiveStepIndex = 3;
}
}
}
protected void WizardStep4_Activate(object sender, System.EventArgs e)
{
lblOutput.Text = ("First Name : "

43

+ (txtFirstName.Text.ToString() + ("<br>" + ("Last Name : "


+ (txtLastName.Text.ToString() + ("<br>" + ("E-mail : " +
txtEmail.Text.ToString())))))));
}
Output:

XML control:
The XML control in ASP.NET is used to read the XML file. Another file is .xsl file which
is used to display the XML data with formatting. The DocumentSource property sets
the path of XML file and TransformSource property sets the path of .Xsl file. In this
example we make a XML file(Employee.xml) and a xsl file(Employee.xsl).
Example :
Employee.xml file:
<?xml version="1.0" encoding="utf-8" ?>
<employee>
<person>
<name>Manish</name>
<post>Java Developer</post>
<department>Development</department>
<mobileno>8785685868</mobileno>
<city>Delhi</city>
<age>26</age>
</person>
<person>
<name>Rahul</name>
<post>Manager</post>
<department>Account</department>
<mobileno>453543546</mobileno>
<city>Banglore</city>
<age>30</age>
</person>
<person>
<name>Ritesh</name>
<post>PHP Developer</post>
<department>Development</department>
<mobileno>567457457</mobileno>
<city>Mumbai</city>
<age>28</age>
</person>
<person>
<name>Amit</name>

44

<post>Engineer</post>
<department>Civil</department>
<mobileno>435464666</mobileno>
<city>Noida</city>
<age>35</age>
</person>
</employee>
Employee.xsl file:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:template match="/">
<html>
<body>
<h2><xsl:value-of select="employee/name" /></h2>
<table width="300" border="1">
<xsl:for-each select="employee/person">
<tr>
<td>
<b>Name: <xsl:value-of select="name" /></b><br />
Post: <xsl:value-of select="post" /><br />
Department: <xsl:value-of select="department" /><br />
Mobile No.: <xsl:value-of select="mobileno" /><br />
City: <xsl:value-of select="city" /><br />
Age: <xsl:value-of select="age" />
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Design:

Source code:
<asp:Xml ID="Xml1" runat="server" DocumentSource="~/XML/Employee.xml"
TransformSource="~/Employee.xslt"></asp:Xml>
Output:

45

MultiView control:
The MultiView control represents a control that acts as a container for groups of
View controls. It allows you to define a group of View controls, where each View
control contains child controls.
Example:

46

Source Code:
<asp:DropDownList ID="DropDownList1"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
runat="server" AutoPostBack="True">
<asp:ListItem Value="0">View 1</asp:ListItem>
<asp:ListItem Value="1">View 2</asp:ListItem>
<asp:ListItem Value="2">View 3</asp:ListItem>
</asp:DropDownList>
Code:
protected void DropDownList1_SelectedIndexChanged(object sender,
System.EventArgs e)
{
MultiView1.ActiveViewIndex = Convert.ToInt32(DropDownList1.SelectedValue);
}
Note : To activate first view MultiView1.ActiveViewIndex =0;
Output:

47

Panel Control:
The Panel Web server control provides a container within the page for other controls.
By putting controls into a Panel control, you can control them as a unit for
example, hiding or showing them. You can also use a Panel control to create a
distinct appearance for a group of controls.
Example:
In this example we declare one Panel control, and one CheckBox control in an .aspx
file. When the user checks the CheckBox control, the Panel control will hide.

Code:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked)
{
Panel1.Visible = false;
}
else
{
Panel1.Visible = true;
}
}
PlaceHolder Control:
The ASP.NET PlaceHolder Web server control enables you to place an empty
container control in the page and then dynamically add child elements to it at run
time. The following topics provide information on working with the PlaceHolder Web
server control.

48

Note: The PlaceHolder control does not produce any visible output (it only acts as a
container for other controls on the Web page).
Example : Generate hyperlink at runtime.
For that, Place four placeholder in your webpage.
Code:
protected void Page_Load(object sender, EventArgs e)
{
HyperLink hyperlink1 = new HyperLink();
hyperlink1.Text = "Devmanuals";
hyperlink1.NavigateUrl = "http://www.devmanuals.com/";
PlaceHolder1.Controls.Add(hyperlink1);
HyperLink hyperlink2 = new HyperLink();
hyperlink2.Text = "Google";
hyperlink2.NavigateUrl = "http://www.google.com/";
PlaceHolder2.Controls.Add(hyperlink2);
HyperLink hyperlink3 = new HyperLink();
hyperlink3.Text = "Yahoo";
hyperlink3.NavigateUrl = "http://www.yahoo.com/";
PlaceHolder3.Controls.Add(hyperlink3);
HyperLink hyperlink4 = new HyperLink();
hyperlink4.Text = "Roseindia";
hyperlink4.NavigateUrl = "http://www.roseindia.net/";
PlaceHolder4.Controls.Add(hyperlink4);
}
Output:

Substitution control:
The Substitution control specifies a section on an output-cached Web page that is
exempt from caching. Use the Substitution control to specify a section on an outputcached Web page where you want dynamic content substituted for the control.
Alternatively, a developer can place a Substitution server control at the page location
where content should be substituted, and set its MethodName property to the
callback method. Unlike Response.WriteSubstitution, which can accept a callback
method on an arbitrary object, the Substitution server controls MethodName

49

property must be set to a static method on the controls containing Page or


UserControl.
Design :

Source code:
<asp:Substitution ID="Substitution1" runat="server"
MethodName="GetCurrentDate" />
Code:
public partial class How_to_use_Substitution_c : System.Web.UI.Page
{
static string GetCurrentDate(HttpContext context)
{
return DateTime.Now.ToString();
}
}
Output:

Localize Control:
Creates a location on a Web page to display localized, static text.
In the following example we declare one Calendar control in an .aspx file. Add
Culture="de-DE" for Germany Calendar.

Source code:
Germany Calendar<asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>

50

Chapter 4 : Navigation Controls


Navigation controls Enable you to add various types of menus to Web pages.
These include static and fly-out menus, a tree view, and a navigation path.
Menu Control:
The Menu control is used to display menus. The menu can be displayed vertically or
horizontally. Below are two screenshots showing vertical and horizontal menus:
Horizontal Menu:

Vertical Menu:

For making a menu change its orientation you just need


the Orientation property of the Menu control to Horizontal or Vertical.

to

change

TreeView Control:
TreeView control in ASP.NET is used Navigation. TreeView control is a Navigation
control. It supports a variety of programming models, from statically-defined trees,
to dynamically constructed trees, to databound trees. You can bound the data with
TreeView control by using SiteMapDataSource or XMLDataSource. It is rendered a
tree view UI. In this example we use the SiteMapDataSource for bind the data with
TreeView. You can see the following how can I use the AutoFormat for TreeView.

51

Design:

Web.sitemap file:
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="http://www.devmanuals.com/" title="ASP.NET"
description="ASP.NET Tutorials">
<siteMapNode
url="http://www.devmanuals.com/tutorials/ms/aspdotnet/index.html"
title="Controls" description="Standards Controls">
<siteMapNode url="~/TextBox.aspx" title="TextBox" description="TextBox
Control"/>
<siteMapNode url="~/BulletList.aspx" title="BulletList" description="BulletList
Control"/>
<siteMapNode url="~/Image.aspx" title="Image" description="Image Control"/>
<siteMapNode url="~/ImageMap.aspx" title="ImageMap" description="ImageMap
Control"/>
</siteMapNode>
<siteMapNode url="~/requiredfieldvalidator.html" title="Validator"
description="Validation Controls">
<siteMapNode url="~/RequiredFieldValidator.aspx" title="RequiredFieldValidator"
description="RequiredFieldValidator"/>
<siteMapNode url="~/CompareValidator.aspx" title="CompareValidator"
description="CompareValidator"/>
<siteMapNode url="~/RangeValidator.aspx" title="RangeValidator"
description="RangeValidator"/>

52

<siteMapNode url="~/RegularExpressionValidator.aspx"
title="RegularExpressionValidator" description="RegularExpressionValidator"/>
<siteMapNode url="~/CustomValidator.aspx" title="CustomValidator"
description="CustomValidator"/>
<siteMapNode url="~/ValidationSummary.aspx" title="ValidationSummary"
description="ValidationSummary"/>
</siteMapNode>
</siteMapNode>
</siteMap>
Source Code:
<asp:TreeView ID="TreeView1" runat="server" ImageSet="Simple"
DataSourceID="SiteMapDataSource1">
<HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />
<NodeStyle Font-Names="Tahoma" Font-Size="10pt" ForeColor="Black"
HorizontalPadding="0px" NodeSpacing="0px" VerticalPadding="0px" />
<ParentNodeStyle Font-Bold="False" ImageUrl="~/Images/bullet-red.png" />
<RootNodeStyle ImageUrl="~/Images/bullet.png" />
<SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD"
HorizontalPadding="0px" VerticalPadding="0px" />
</asp:TreeView>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
Output:

SiteMap Path:
The SiteMapPath control displays a list of links representing the users current page
and the hierarchal path back to the root of the website.

53

Chapter - 5 Validation Controls


Ever since the first dynamic website was created, form validation has been an
important subject. Getting user input through the system requires much attention,
and with previous serverside scripting languages, there were no standard way of
dealing with form validation. For that reason, clientside scripting has been used in
many cases, but as you probably know, clientside scripting is not bulletproof - it can
easily be bypassed or simply turned off. With ASP.NET, webdevelopers were finally
given a good, standard set of tools for validating forms. The validation controls of
ASP.NET is based on both clientside and serverside technology, which brings the best
from both worlds, to make sure that validating a form is as easy as ever.
ASP.NET 2.0, which is the latest version as I write this, comes with several different
validation controls for different purposes. They all work in different ways, but
essentially they do the same - they make sure that a form field has been properly
filled by the user.
(1) Required Field Validator :
The RequiredFieldValidator is actually very simple, and yet very useful. You can
use it to make sure that the user has entered something in a TextBox control. Let's
give it a try, and add a RequiredFieldValidator to our page. We will also add a
TextBox to validate, as well as a button to submit the form with.
<form id="form1" runat="server">
Your name:<br />
<asp:TextBox runat="server" id="txtName" />
<asp:RequiredFieldValidator runat="server" id="reqName"
controltovalidate="txtName" errormessage="Please enter your name!" />
<br /><br />
<asp:Button runat="server" id="btnSubmitForm" text="Ok" />
</form>

Actually, that's all we need to test the most basic part of the RequiredFieldValidator.
I'm sure that all the attributes of the controls makes sense by now, so I won't go
into details about them. Try running the website and click the button. You should see
something
like
this:

If your browser supports DHTML, which most modern browers do, then you will
notice that the page is not being posted back to the server - the validation is
performed clientside! This is one of the really cool things about ASP.NET validators.
Validation is only performed serverside if necessary! To see how it feels, you can add
enableclientscript="false" to the RequiredFieldValidator and try again. Now you will
see the browser posting back to the server, but the result will be the same
the validator still works!

54

Right now, the button does nothing, besides posting back if the page is valid. We will
change this by adding an onclick event to it:
<asp:Button runat="server" id="btnSubmitForm" text="Ok"
onclick="btnSubmitForm_Click" />

In the CodeBehind file, we add the following event handler:


protected void btnSubmitForm_Click(object sender, EventArgs e)
{
if(Page.IsValid)
{
btnSubmitForm.Text = "My form is valid!";
}
}

As you will notice, we check whether or not the page is valid, before we do anything.
This is very important, since this code WILL be reached if the clientside validation is
not used, for some reason. Once it comes to serverside validation, it's your job to
make sure that no sensitive code is executed unless you want it to. As you see, it's
very simple - just check the Page.IsValid parameter, and you're good to go. Try to
run the website again, and notice how the text of the button is changed if you
submit a valid form.
(2) Compare Validator :
The CompareValidator might not be the most commonly used validator of the
bunch, but it's still useful in some cases. It can compare two values, for instance the
values of two controls. In the next example, I will show you a small example of how
it can be used.
Small number:<br />
<asp:TextBox runat="server" id="txtSmallNumber" /><br /><br />
Big number:<br />
<asp:TextBox runat="server" id="txtBigNumber" /><br />
<asp:CompareValidator runat="server" id="cmpNumbers"
controltovalidate="txtSmallNumber" controltocompare="txtBigNumber"
operator="LessThan" type="Integer" errormessage="The first number should be
smaller than the second number!" /><br />

As you see, we only use one validator to validate the two fields. It might seem a bit
overwhelming, but it's actually quite simple. Like with the RequiredFieldValidator, we
use the controltovalidate attribute to specify which control to validate. In addition to
that, we specify a control to compare. The operator attribute specifies which method
to use when comparing. In this case, we use the LessThan operator, because we
wish for the first control to have the smallest value. We set the type to integer,
because we want to compare integers. Dates, strings and other value types can be
compared
as
well.
Now, try running the website, and test the two new fields. Here is what happens if
you
don't
fill
out
the
form
correctly:

55

If you switch the numbers, you will see another cool thing about the ASP.NET
validators and clientside scripting: Validation is also performed upon exiting the
fields. If you don't want this, you can turn off clientside scripting with the
enableclientscript attribute. You can also compare a field to a static value. To do this,
remove the controltocompare attribute, and add the valuetocompare attribute.
However, as you may have noticed, the content of the two textboxes is not checked
before comparing it. For instance, it would be possible to enter nothing, or enter a
piece of text instead of a number. You should always consider this when using the
CompareValidator.
You
can
protect
against
empty
fields
with
the
RequiredFieldValidator, and you can protect against wrong values like text with for
instance a RegularExpressionValidator.
(3) Range Validator :
The RangeValidator does exactly what the name implies; it makes sure that the
user input is within a specified range. You can use it to validate both numbers,
strings and dates, which can make it useful in a bunch of cases. Since we validated
numbers the last time, we will try with a date this time.
Date:<br />
<asp:TextBox runat="server" id="txtDate" />
<asp:RangeValidator runat="server" id="rngDate" controltovalidate="txtDate"
type="Date" minimumvalue="01-01-2006" maximumvalue="31-12-2006"
errormessage="Please enter a valid date within 2006!" />

The date format might seem a bit weird to you if you're not from Europe, where we
use dd-mm-yy. You can just change it if it doesn't fit the date format on the machine
you're working on. Now, try running the website, and enter a date in our new
TextBox. It's only valid if the date is within 2006, and a cool sideeffect is that the
date is also checked for validity. Have a look at this screenshot, which shows us that
the
validator
reacts
to
an
impossible
date
as
well:

56

(4) Regular Expression Validator :


The RegularExpressionValidator is a bit more difficult to write about, because it
requires knowledge of Regular Expressions to really use it. However,
RegularExpressionValidator is one of the most useful validators, because it can be
used to check the validity of any kind of string. If you don't feel like learning Regular
Expressions, but still feel like using this validator, have a look around the Internet.
You can find many pre-made expressions out there, which can be very useful to you.
Here is an example where we require a 4 digit number - nothing else is acceptable:
4 digit number:<br />
<asp:TextBox runat="server" id="txtNumber" />
<asp:RegularExpressionValidator runat="server" id="rexNumber"
controltovalidate="txtNumber" validationexpression="^[0-9]{4}$"
errormessage="Please enter a 4 digit number!" />
<br />

The only new attribute we use, is the validationexpression. This attribute simply
holds the Regular Expression which should be used to validate the field. Since
Regular Expressions are beyond the scope of this tutorial, I won't try to explain it,
other than it simply tells the validator that a value of 4 digits are acceptable, and
nothing else. You can use the RegularExpressionValidator for almost everything, for
instance
validating
an
e-mail
or
an
URL.
Try switching to Design view and select the RegularExpressionValidator on your
page. Now have a look in the Properties tab. The ValidationExpression attribute has
a button next to it, and if you click it, you will gain access to some default
expressions, delivered by the ASP.NET team, for various purposes. Just select one of
them, to use in your validator.
(5) Custom Validator :
If none of the other validators can help you, the CustomValidator usually can. It
doesn't come with a predefined way of working; you write the code for validating
your self. This is of course very powerful, since the possibilities are basically endless.
A common way of using the CustomValidator is when you need to make a database
lookup to see if the value is valid. Since this tutorial hasn't treated database access
yet, we will do a simpler example, but hopefully you will see that you can do just
about everything with the CustomValidator. The control allows you to validate both
clientside and serverside, where the serverside approach is probably the most
powerful. Of course, doing serverside validation requires a postback to validate, but
in
most
cases,
that's
not
really
a
problem.
In this example, we will simply check the length of the string in the TextBox. This is
a very basic and that useful example, only made to show you how you may use the
CustomValidator.
Custom text:<br />
<asp:TextBox runat="server" id="txtCustom" />

57

<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom"


onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly
8 characters long!" />

As you can see, it's pretty simple. The only unknown property is
the onservervalidate event. It's used to reference a method from CodeBehind which
will handle the validation. Switch to our CodeBehind file and add the following
method:
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
if(e.Value.Length == 8)
e.IsValid = true;
else
e.IsValid = false;
}
This is very simple. The validator basically works by setting the e.IsValid boolean
value to either true or false. Here we check the e.Value, which is the string of the
control being validated, for it's length. If it's exactly 8 characters long, we return
true, otherwise we return false.
(6) Validation Summary :
The ValidationSummary control allows you to summarize the error messages from
all validation controls on a Web page in a single location. The summary can be
displayed as a list, a bulleted list, or a single paragraph, based on the value of
the DisplayMode property.
The
error
message
displayed
in
the ValidationSummary control for each validation control on the page is specified
by
the ErrorMessage property
of
each
validation
control.
If
the ErrorMessage property of the validation control is not set, no error message is
displayed in the ValidationSummary control for that validation control. You can
also
specify
a
custom
title
in
the
heading
section
of
the ValidationSummary control by setting the HeaderText property.
You can control whether the ValidationSummary control is displayed or hidden by
setting the ShowSummary property. The summary can also be displayed in a
message box by setting the ShowMessageBox property to true.
More Validation
The validators all share a couple of attributes, which can be very useful in some
cases.
ValidationGroup
This attribute was introduced with ASP.NET 2.0, and makes it possible to divide your
form elements into groups. Usually, a validator control is always triggered on a
postback, which could sometimes lead to problems. For instance, if you have a
contact form and a search field on the same page, the validation of the contact form
could be triggered by the Search button, preventing the user from searching before
filling out the contact form. You can assign a name in the validationgroup property,
for both the validators and the button(s) that you wish to be able to trigger the

58

validation. The value of the attribute can be a number or a name, like


validationgroup="contact_form".
SetFocusOnError (true|false)
This attribute was also introduced with ASP.NET 2.0, and it does exactly what the
name implies. Set SetFocusOnError to true on one or several of your validators, to
give focus to the first invalid field when the form is validated.
Display (Dynamic|None|Static)
This attribute decides how the validator is rendered to your page. The default value
is Static, which makes the validator take up the required place whether it's visible
(active) or not. You can test this by placing a piece of text directly behind a validator
and load the page. If you have not set the Display attribute, or if you have set it to
Static, you will see that the text is moved. However, if you set it to Dynamic, the
validator will only take up any space if the validation fails and the validator is
activated. This can be convenient in some cases, where you need the space the
validator can take up otherwise. If you set it to None, the error message will never
be shown.

59

Chapter 6 Login Controls


Login controls Enable you to easily create logon forms and authenticate users. You
can also use login controls that enable users to register on the Web site and recover
or replace their passwords.

Login:
ASP.Net 2.0 login control provides the interface as well as in-built functionality of
user login. Login control uses the default sql membership provider that authenticates
the username and password for a specific account.

UserName
Username input field accepts the login user name to be entered by the
member user.
Password
Password input field accepts the secret password for the username entered in
Username input field.
Remember
me
checkbox
Remember me checkbox provides the functionality that keeps the user logged
in if user does not logout after last login. Remember me function drops a
cookie on the clients system that keeps the user logged in until the cookie
expires or user clicks logout button.
Login
button
Login button sends the username and password to the membership provider
for authentication.
Properties

Property

Description

CreateUserText

CreateUserText property displays the text for create user


link in the login control.

CreateUserUrl

CreateUserUrl property accepts the URL of the page


having user registration form.

DestinationPageUrl

DestinationPageUrl property takes the URL of the page


that directs the user to the destination page upon
successful login.

DisplayRemeberMe

DisplayRemeberMe

60

property

sets

remember

me

functionality on or off.
Orientation

Orientation property sets the horizontal or vertical layout


of the login control interface.

RememberMeSet

RememberMeSet property, if it is true then displays


remember me checkbox initially checked.

TextLayout

TextLayout property sets the TextOnLeft or TextOnTop for


the labels used for username and password

VisibleWhenLoggedI VisibleWhenLoggedIn property hides the login control if


n
its value is false
LoginView:
LoginView provides the functionality to create different views for the users of
different Roles. LoginView control consists of 3 different templates:
Templet

Description

AnonymousTemplat AnonymousTemplate of LoginView control can be used to


e
display the default view of the LoginView that can be
viewed by unauthenticated, guest or anonymous user. You
can place the link to login page or login control inside the
AnonymousTemplate. LoginView Control displays the
content and controls of AnonymousTemplate if there is no
user logged in.
LoggedInTemplate

LoginView Control detects the login status of the user, if


membership provider gets the status as authenticated
user has logged in then it displays the view provided by
the LoggedInTemplate. You can display the LoginStatus,
LoginName
of
the
current logged in user in
LoggedInTemplate.

RoleGroups

RoleGroups Template consists of collection of templates


for different roles stored in the default aspnetdb database
that provides the feature of membership as well as roles
management. RoleGroups is further divided into
asp:RoleGroup that has an attribute to set the Roles to
associate the view with any particular role. asp:RoleGroup
consists of ContentTemplate that accommodates the set
of controls placed inside it to generate the role associated
view.

Note: When RoleGroups template is used in LoginView Control then it automatically


detects the role of logged in user and displays the role associated view for that role
based user. If the current logged in user has not been assigned any role then
LoginView displays the LoggedInTemplate view for that user.
PasswordRecovery Control:

61

The Password Recovery control provides the functionality to reset or


recovery the old password for the username specified for the password recovery.
Password recovery control works in 3 steps to retrieve the password from the
database and sends an email at the authenticated email address provided by the
user at the time of registration.
The PasswordRecovery control displays 3 different views like a wizard of 3
moves. In the first view it displays a UserName textbox and a submit button.
When user inputs a UserName and submits it then Membership provider service
verifies the user existence in the database, if user exists then it displays the second
view asking the security question to authenticate the user. If authentication by
security question and answer succeeds then PasswordRecovery control displays the
third view with a message "Your password has been sent to you."
LoginStatus control:
LoginStatus control also works with sql membership provider of asp.net 2.0 that
detects the status of user currently logged in or not. If user is currently logged in
then LoginStatus control displays the logout button and if the user has not logged
in the web site or the user is viewing the page anonymously then LoginStatus
Control displays the login button.
You can also change the logout page destination by setting LoginStatus Control
properties as following:
LogoutAction
LogoutAction property consists of 3 values:
Refresh: refreshes the current web page when user clicks on logout button.
Redirect: redirects the user to the page specified in the LogoutPageUrl
property if LoginStatus Control
RedirectToLoginPage: redirects to the login page specified in the Forms
authentication section of web.config file as discussed above.

Property
LogoutPageUrl

Description
LogoutPageUrl property accepts the URL to which it
redirects the user when he clicks on logout button.

LoginName:
LoginName control displays the UserName of the authenticated user
currently logged into the web site. LoginName also uses the sql membership
provider
to
retrieve
the
authenticated
username.
It
uses
the
Page.User.Identity.Name to get the UserName of the currently logged in user.
If the user is not logged in then LoginName control does not render on web
page and does not hold any space block on the page.
LoginName Control FormatString
FormatString property of the LoginName control enables you to customize
the string and UserName that can be displayed in the control. For example if you
want to display the greeting message followed by UserName then you can set the
FormatString
value
=
Hi
{0}!
Above value for FormatString will display Hi followed by UserName of the logged in
user.
{0} is automatically replaces by the username when LoginName control is
rendered on the page if any user is currently logged in.

62

Create User Wizard Control:

In ASP.Net 2.0 membership CreateUser Wizard Control provides the


automated functionality to register a new user on your web site. It uses the default
sql provider that connects to Aspnetdb database to save the membership data.
CreateUser Wizard Control uses the Wizard control of ASP.Net that relies on
membership services to create and manage personalized data in aspnetdb database.
CreateUserWizardStep Template
CreateUserWizardStep template consists of following input fields to create a valid
user:
1. UserName: unique ID for new user that will be used as login username
2. Password: password to authenticate user login.
3. ConfirmPassword: re-enter the password for verification during create user
wizard.
4. Email: a valid Email-ID for sending accounts related information to the user.
5. Question: Security Question to verify the user at the time of password
recovery.
6. Answer: Secret answer for security question.
Create User button passes a command CreateUser to the membership provider that
creates a new user in the database without any code behind the button click event
to create user.
All input fields of CreateUserWizardStep are validated by required field
validation controls of ASP.Net. You can also validate the Email field by using Email
Validation Regular Expression. Set the EmailRegularExpression property of
createuserwizard
control
=
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+
([-.]\w+)* to validate the user Email-Id string value.
CompleteWizardStep Template
When user clicks on CreateUser button, it creates the user in database and changes
the create user wizard step to CompleteWizardStep. By default CompleteWizardStep
template displays "Your account has been successfully created." message and
Continue button.
You can change the message by changing the CompleteSuccess property of
CreateUser Wizard control.
You can set the ContinueDestinationPageUrl property to redirect the user to a
particular web page when user clicks on Continue button after successful
registration.
So, just drag and drop the Create User Wizard Control from login controls tab on
your web page, you are ready with user registration step of ASP.Net membership
function.

63

ChangePassword Control:

The ChangePassword Control in ASP.Net 2.0 provides the in-built functionality to


change the password of authenticated or logged in user. ChangePassword control by
default shows input fields for old Password, new password, confirm new password.
First to confirm that the user has accessed the page through proper channel via
login page, ChangePassword Control takes the old Password to verify the user
identity in the database. Next it accepts the new password that is stored into the
database after confirmation.
Following are some properties of ChangePassword Control that customizes the
behavior of change password wizard:
Property

Description

CancelDestinationPageUrl:

You can specify the destination page URL for the


cancel
button
in
CancelDestinationPageUrl
property. Cancel button will redirect the user to
the specified URL when he clicks to cancel the
action.

SuccessPageUrl:

You can specify the success page URL in


SuccessPageUrl property to direct the user to
another page after changing the password
successfully.
If
you
will
specify
the
SuccessPageUrl then ChangePassword Control will
bypass the success view of the control.

PasswordHintText:

You can display the password guidelines or hint


using this property e.g.: must be 8 characters
and contain at least 1 non-alphabetic character.

If you are using the ChangePassword Control in the administrative control panel of
your ASP.Net web site then you can use following additional properties to provide
more features to the administrator:
CreateUserText: Enter text for the link to create user page.
CreateUserUrl: URL of the create user page.
DisplayUserName: You can set it true/false to display the username textbox in the
ChangePassword Control. Administrator can change the password of different users
by passing different username and password.

64

Chapter 7 MasterPage / Theme / CSS


Master Pages:
ASP.NET master pages allow you to create a consistent layout for the pages in
your application. A single master page defines the look and feel and standard
behavior that you want for all of the pages (or a group of pages) in your application.
You can then create individual content pages that contain the content you want to
display. When users request the content pages, they merge with the master page to
produce output that combines the layout of the master page with the content from
the content page.
Master pages allow you to create a consistent look and behavior for all the
pages (or group of pages) in your web application. A master page provides a
template for other pages, with shared layout and functionality. The master page
defines placeholders for the content, which can be overridden by content pages. The
output result is a combination of the master page and the content page. The content
pages contains the content you want to display.
When users request the content page, ASP.NET merges the pages to produce output
that combines the layout of the master page with the content of the content page.

Advantages of Master Pages:


Master pages provide functionality that developers have traditionally created by
copying existing code, text, and control elements repeatedly; using framesets; using
include files for common elements; using ASP.NET user controls; and so on.
Advantages of master pages include the following:
They allow you to centralize the common functionality of your pages so that
you can make updates in just one place.
They make it easy to create one set of controls and code and apply the
results to a set of pages. For example, you can use controls on the master
page to create a menu that applies to all pages.
They give you fine-grained control over the layout of the final page by
allowing you to control how the placeholder controls are rendered.
They provide an object model that allows you to customize the master page
from individual content pages.
Run-time Behavior of Master Pages:

At run time, master pages are handled in the following sequence:


1. Users request a page by typing the URL of the content page.
2. When the page is fetched, the @ Page directive is read. If the directive
references a master page, the master page is read as well. If this is the first
time the pages have been requested, both pages are compiled.
3. The master page with the updated content is merged into the control tree of
the content page.
65

4. The content of individual Content controls is merged into the corresponding


ContentPlaceHolder control in the master page.
5. The resulting merged page is rendered to the browser.
The process is illustrated in the following diagram.

Master pages at run time

66

Theme:
Creating A Theme:
Themes, unlike master page files, need to live underneath a special directory by the
name of App_Themes. Visual Studio will add an App_Themes folder to a web
application when you right click the web project, select Add Folder from the context
menu, and select the Theme folder item.
Also unlike master pages (which are single files), themes consist of a collection of
files. A theme may contain .skin files, style sheets, and even image files. To organize
and name themes, we use subfolders in App_Themes. In the following screen shot,
we have a theme by the name of Odeish and a theme by the name of Codeish.

Inside of our Odeish folder we will create a .skin file. You can add as many .skin files
to a theme as you need. Each skin file will contain one or more control skins. A
control skin specifies the property settings to apply to a specific type of control.

Themes and CSS:


To apply a default stylesheet for a theme, all you need to do is create a .css file
within the appropriate theme folder in the Themes directory. For example, you could
place a css file called DefaultStyle.css within the Themes\DefaultStyle folder. When

67

you specify the DefaultTheme in the theme attribute of the @page directive in a
page, the DefaultStyle.css file is automatically applied. Note that you can still apply
a stylesheet manually in the HTML by specifying the Link element in the head tag.
You can actually place more than one stylesheet file within a theme folder - in which
case ASP.NET will attempt to apply all stylesheets in that theme folder to the site,
combining definitions contained in all the CSS files.
Themes versus CSS Style Sheets:
Themes are similar to CSS style sheets in that both themes and style sheets define a
set of common attributes that apply to any page where the theme or style sheet is
applied. However, themes differ from style sheets in the following ways:
Themes can define many properties of a control or page, not just a specific
set of style properties. For example, using themes, you can specify the
graphics for a TreeView control, the template layout of a GridView control,
and so on.
Themes can include auxiliary files, such as graphics, that can't be included in
a CSS style sheet.
Themes do not cascade the way style sheets do; for example, theme property
values always override local property values.
Themes can include style sheet references. In that case, the style sheet
definitions are applied along with other property values defined in the theme.
Skin file :
There are two types of control skins, default skins and named skins:
A default skin automatically applies to all controls of the same type when a theme is
applied to a page. A control skin is a default skin if it does not have a SkinID
attribute. For example, if you create a default skin for a Calendar control, the control
skin applies to all Calendar controls on pages that use the theme. (Default skins are
matched exactly by control type, so that a Button control skin applies to all Button
controls, but not to LinkButton controls or to controls that derive from the Button
object.)
A named skin is a control skin with a SkinID property set. Named skins do not
automatically apply to controls by type. Instead, you explicitly apply a named skin to
a control by setting the control's SkinID property. Creating named skins allows you
to set different skins for different instances of the same control in an application.
Applying Skins to Controls
Skins defined in your theme apply to all control instances in the application or pages
to which the theme is applied. In some cases, you might want to apply a specific set
of properties to an individual control. You can do that by creating a named skin (an
entry in a .skin file that has a SkinID property set) and then applying it by ID to
individual controls.

To apply a named skin to a control


Set the control's SkinID property, as shown in the following example:

68

<asp:Calendar runat="server" ID="DatePicker" SkinID="SmallCalendar" />


If the page theme does not include a control skin that matches the SkinID property,
the control uses the default skin for that control type.
Using Themes to Customize a Site:
The previous section demonstrated a variety of ways to specify styles for controls by
setting style properties on controls themselves. For example, consider the following
page, which has a number of style settings applied to individual controls on the
page.
In addition to specifying styles on individual controls, ASP.NET 2.0 introduces
Themes, which provide an easy way to define the style settings for controls and
pages in your site separately from the pages of your application. The benefit of
Themes is that you can design a site without regard for the style and apply the style
at a later time without having to update the pages or application code. You can also
obtain custom Themes from external sources to apply stylistic settings to your
application. The benefit of a Theme is that the style settings are stored in a single
location that can be maintained separately from the application to which the Theme
is
applied.
The following example demonstrates the same page with a Theme applied in order
to specify the style settings for the control. Notice that the page itself does not need
to contain any style information. The Theme automatically applies style properties at
runtime to controls on the page.
The App_Themes Folder:
Themes reside in the App_Themes folder directly under the application root
directory. A Theme consists of a named subdirectory under this folder that contains
a collection of one or more Skin files, named with the .skin extension. A Theme can
also contain a CSS file and/or subdirectories for static files like images. The figure
below shows an App_Themes directory with two Themes defined, named "Default"
and "White", each of which has a single skin file and CSS file.

Observe in the previous example that the contents of a skin file are simply
control definitions as they might appear in a page. A skin file can contain multiple
control definitions, for example one definition for each control type. The properties
of controls defined in the theme automatically override the local property value for a
control of the same type in the target page with the Theme applied. For example, a
<asp:Calendar Font-Name="Verdana" runat="server"/> control definition in a skin
file will cause all Calendar controls in pages with the Theme applied to use the
Verdana font. A local value for this property on the control will be overridden by the
Theme. Note that it is an error to specify an ID property value for a control
definition in a skin file.
Global and Application Themes:
A Theme can reside at the application-level or machine-level (globally
available to all applications). Application-level Themes are placed in the App_Themes
directory under the application root directory, as described above. Global Themes

69

are placed in a "Themes" directory under the ASP.NET installation direction, for
example %WINDIR%\Microsoft.NET\Framework\<version>\Themes.
Assigning a Theme to a Page:
An individual page can be assigned a Theme by setting the <%@ Page
Theme="..." %> directive to the name of a global or application-level Theme (the
name of a folder under the Themes or App_Themes directory). A page can only have
one Theme applied, but there may be multiple skin files in the theme that apply
style settings to controls in the page.
Assigning a Theme in Config:
You can also define the applied theme for all pages in an application by
specifying the <pages theme="..."/> section in Web.config. To unset this theme for
a particular page, you can set the Theme attribute of the Page directive to empty
string (""). Note that a master page cannot have a Theme applied; you should set
the Theme on content pages or in configuration (described below) instead.
Exmaple:
Creating a Master Page
1. Add a master page to the site in the root directory by right-clicking on the Project
name, choosing Add New Item, and selecting the Master Page template. Note that
master pages end with the extension .master. Name this new master
page Site.master and click Add.

70

2. Expand Site.master's default declarative markup to create a site layout where all
pages share: a common header; a left column with navigation, news and other sitewide content; and a footer that displays the Message.
3. With the master page created, we are ready to start creating ASP.NET pages that
are bound to the master page. Such pages are referred to as content pages.
Let's add a new ASP.NET page to the project and bind it to the Site.master master
page. Right-click on the project name in Solution Explorer and choose the Add New
Item option. Select the Web Form template, enter the name About.aspx, and then
check the "Select master page" checkbox as shown in Figure 7. Doing so will display
the Select a Master Page dialog box (see Figure 8) from where you can choose the
master page to use.

71

Select the Site.master Master Page.


As the following declarative markup shows, a new content page contains
a @Page directive that points back to its master page and a Content control for each
of the master page's ContentPlaceHolder controls.
<%@ Page Language="C#" MasterPageFile="~/Site.master"
AutoEventWireup="true" CodeFile="About.aspx.cs" Inherits="About" Title="Untitled
Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
Runat="Server">
</asp:Content>
4. Take a moment to create some content for the About.aspx page. Entered any
heading and a couple of paragraphs of text, but feel free to add Web controls, too.
After creating this interface, visit the About.aspx page through a browser.
It is important to understand that the requested content page and its associated
master page are fused and rendered as a whole entirely on the web server.

72

Chapter 8 ADO .NET


Most applications need data access at one point of time making it a crucial
component when working with applications. Data access is making the application
interact with a database, where all the data is stored. Different applications have
different requirements for database access. VB .NET uses ADO .NET (Active
X Data Object) as it's data access and manipulation protocol which also enables us
to work with data on the Internet. Let's take a look why ADO .NET came into picture
replacing ADO.
Evolution of ADO.NET
The first data access model, DAO (data access model) was created for local
databases with the built-in Jet engine which had performance and functionality
issues. Next came RDO (Remote Data Object) and ADO (Active Data Object) which
were designed for Client Server architectures but, soon ADO took over RDO. ADO
was a good architecture but as the language changes so is the technology. With
ADO, all the data is contained in a recordset object which had problems when
implemented on the network and penetrating firewalls. ADO was a connected data
access, which means that when a connection to the database is established the
connection remains open until the application is closed. Leaving the connection open
for the lifetime of the application raises concerns about database security and
network traffic. Also, as databases are becoming increasingly important and as they
are serving more people, a connected data access model makes us think about its
productivity. For example, an application with connected data access may do well
when connected to two clients, the same may do poorly when connected to 10 and
might be unusable when connected to 100 or more. Also, open database connections
use system resources to a maximum extent making the system performance less
effective.
Why ADO.NET?
To cope up with some of the problems mentioned above, ADO .NET came into
existence. ADO .NET addresses the above mentioned problems by maintaining
a disconnected database access model which means, when an application interacts
with the database, the connection is opened to serve the request of the application
and is closed as soon as the request is completed. Likewise, if a database is
Updated, the connection is opened long enough to complete the Update operation
and is closed. By keeping connections open for only a minimum period of time,
ADO .NET conserves system resources and provides maximum security for
databases and also has less impact on system performance. Also, ADO .NET when
interacting with the database uses XML and converts all the data into XML
format for database related operations making them more efficient.
The ADO.NET Data Architecture
Data Access in ADO.NET relies on two components: DataSet and Data Provider.
DataSet

73

The dataset is a disconnected, in-memory representation of data. It can be


considered as a local copy of the relevant portions of the database. The DataSet is
persisted in memory and the data in it can be manipulated and updated independent
of the database. When the use of this DataSet is finished, changes can be made
back to the central database for updating. The data in DataSet can be loaded from
any valid data source like Microsoft SQL server database, an Oracle database or
from a Microsoft Access database.
Data Provider
The Data Provider is responsible for providing and maintaining the connection to the
database. A DataProvider is a set of related components that work together to
provide data in an efficient and performance driven manner. The .NET Framework
currently comes with two DataProviders: the SQL Data Provider which is designed
only to work with Microsoft's SQL Server 7.0 or later and the OleDb
DataProvider which allows us to connect to other types of databases like Access and
Oracle. Each DataProvider consists of the following component classes:
The Connection object
which
provides a
connection
to
the
database
The Command object
which
is
used
to
execute
a
command
The DataReader object which provides a forward-only, read only, connected
recordset
The DataAdapter object which populates a disconnected DataSet with data and
performs update

Data access with ADO.NET can be summarized as follows:


A connection object establishes the connection for the application with the database.
The command object provides direct execution of the command to the database. If
the command returns more than a single value, the command object returns a
DataReader to provide the data. Alternatively, the DataAdapter can be used to fill
the Dataset object. The database can be updated using the command object or the
DataAdapter.

74

Component classes that make up the Data Providers


The Connection Object
The Connection object creates the connection to the database. Microsoft Visual
Studio .NET provides two types of Connection classes: the SqlConnection object,
which is designed specifically to connect to Microsoft SQL Server 7.0 or later, and
the OleDbConnection object, which can provide connections to a wide range of
database types like Microsoft Access and Oracle. The Connection object contains all
of the information required to open a connection to the database.
The Command Object

75

The
Command
object
is
represented
by
two
corresponding
classes: SqlCommand and OleDbCommand. Command objects are used to execute
commands to a database across a data connection. The Command objects can be
used to execute stored procedures on the database, SQL commands, or return
complete tables directly. Command objects provide three methods that are used to
execute commands on the database:
ExecuteNonQuery: Executes commands that have no return values such as INSERT,
UPDATE or DELETE
ExecuteScalar: Returns a single value from a database query
ExecuteReader: Returns a result set by way of a DataReader object
The DataReader Object
The
DataReader
object
provides
a forward-only, read-only, connected
stream recordset from a database. Unlike other components of the Data Provider,
DataReader objects cannot be directly instantiated. Rather, the DataReader is
returned as the result of the Command object's ExecuteReader method. The
SqlCommand.ExecuteReader method returns a SqlDataReader object, and the
OleDbCommand.ExecuteReader method returns an OleDbDataReader object. The
DataReader can provide rows of data directly to application logic when you do not
need to keep the data cached in memory. Because only one row is in memory at a
time, the DataReader provides the lowest overhead in terms of system performance
but requires the exclusive use of an open Connection object for the lifetime of the
DataReader.
The DataAdapter Object
The DataAdapter is the class at the core of ADO .NET's disconnected data access. It
is essentially the middleman facilitating all communication between the database
and a DataSet. The DataAdapter is used either to fill a DataTable or DataSet with
data from the database with it's Fill method. After the memory-resident data has
been manipulated, the DataAdapter can commit the changes to the database by
calling the Update method. The DataAdapter provides four properties that represent
database commands:
SelectCommand
InsertCommand
DeleteCommand
UpdateCommand
When the Update method is called, changes in the DataSet are copied back to the
database
and
the
appropriate
InsertCommand,
DeleteCommand,
or
UpdateCommand is executed.
The namespace that needs to be imported when working with SQL Connections is
System.Data.SqlClient. This section works with common database operations like
insert, select, update and delete commands.

76

Example:
Insert, Update and Delete data from the table called tblEmp of database Emp.
Create a datCreate a table tblEmp with following structure:
EmpId
numeric
EmpName
varchar

Design:

Code:
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection cn;
SqlDataAdapter da;
SqlCommand cmd;
DataSet ds;
string s;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=D:\websiteSQL\App_Data\Emp.mdf;Inte
gra ted Security=True;User Instance=True");
cn.Open();
dispGrid();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
s="Insert into tblEmp values(" + txtId.Text + " ,'" + txtName.Text + "')";
cmd = new SqlCommand(s, cn);
cmd.ExecuteNonQuery();
dispGrid();
}

77

void dispGrid()
{
s = "Select * from tblEmp";
da = new SqlDataAdapter(s, cn);
ds = new DataSet();
da.Fill(ds, "tblEmp");
grd1.DataSource = ds.Tables[0].DefaultView;
grd1.DataBind();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
s = "Delete from tblEmp where EmpId =" + txtId.Text;
cmd = new SqlCommand(s, cn);
cmd.ExecuteNonQuery();
dispGrid();
}
}
Example 2 : Change the name of employee from the table using same database as
ablove example.
Design :

Output :

Code:
using System.Data.SqlClient;
public partial class Default4 : System.Web.UI.Page
{
SqlConnection cn;
SqlDataAdapter da;
SqlCommand cmd;
DataSet ds;
string s;
protected void Page_Load(object sender, EventArgs e)
{
cn
=
new
SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=D:\Examples\Asp Dot Net Example with
C#\websiteSQL\App_Data\Emp.mdf;Integrated
Security=True;User
Instance=True");
cn.Open();
dispGrid();

78

if (!Page.IsPostBack)
{
s = "Select EmpId from tblEmp";
da = new SqlDataAdapter(s, cn);
ds = new DataSet();
da.Fill(ds, "tblEmp");
DropDownList1.DataTextField = "EmpId";
DropDownList1.DataValueField = "EmpId";
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataBind();
}

void dispGrid()
{
s = "Select * from tblEmp";
da = new SqlDataAdapter(s, cn);
ds = new DataSet();
da.Fill(ds, "tblEmp");
grd1.DataSource = ds.Tables[0];
grd1.DataBind();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
s = "Select * from tblEmp Where EmpId = " + DropDownList1.Text;
da = new SqlDataAdapter(s, cn);
ds = new DataSet();
da.Fill(ds, "tblEmp");
txtName.Text = ds.Tables[0].Rows[0][1].ToString();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
s = "Update tblEmp set EmpName='" + txtName.Text + "' Where EmpId =" +
DropDownList1.Text;
cmd = new SqlCommand(s, cn);
cmd.ExecuteNonQuery();
dispGrid();
}
}

79

Chapter 9 State Management


A new instance of the Web page class is created each time the page is posted to the
server. In traditional Web programming, this would typically mean that all
information associated with the page and the controls on the page would be lost
with each round trip. For example, if a user enters information into a text box, that
information would be lost in the round trip from the browser or client device to the
server. To overcome this inherent limitation of traditional Web programming,
ASP.NET includes several options that help you preserve data on both a per-page
basis and an application-wide basis.
Types of State Management
There are mainly two types of state management that ASP.NET provides:
1. Client side state management
2. Server side state management
When we use client side state management, the state related information will be
stored on client side. This information will travel back and forth with every request
and response. This can be visualized as:

The major benefit of having this kind of state management is that we relieve the
server from the burden of keeping the state related information, it saves a lot of
server memory. The downside of client side state management is that it takes more
bandwidth as considerable amount of data is traveling back and forth. But there is
one more problem which is bigger than the bandwidth usage problem. The client
side state management makes the information travel back and forth and hence this
information can be intercepted by anyone in between. So there is no way we can
store the sensitive information like passwords, credit card number and payable
amount on client side, we need server side state management for such things.
Server side state management, in contrast to client side, keeps all the information in
user memory. The downside of this is more memory usage on server and the benefit
is that users' confidential and sensitive information is secure.

80

We cannot say that we will use any one type of state management in our
application. We will have to find a mix of client side and server side state
management depending on the type and size of information.
Client side state management techniques
View State
Hidden fields
Cookies
Query Strings
Server side state management techniques
Application State
Session State

View State
ASP.NET uses this mechanism to track the values of the controls on the web page
between page request for same page. We can also add custom values to view state.
ASP.NET framework takes care of storing the information of controls in view state
and retrieving it back from viewstate before rendering on postback.
If we need to use viewstate to store our information, we just need to remember that
the viewstate is a dictionary object. We can have our data stored as key value pair in
viewstate (see code below). The controls information is also being hashed into this
dictionary during request and populated back during response.
Since this information is stored in the web page itself, ASP.NET encrypts the
information. We can tweak the encryption related parameters from web.config.
<Configuration>
<system.web>
<pages viewStateEncryptionMode="Always"/>
</system.web>
</configuration>
or page declarative:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default"
ViewStateEncryptionMode="Always"%>

81

Let us now look at a small implementation for viewstate. We have a simple web
page with a textbox and a button. The idea is that we will write something in the
text box and see how ASP.NET stores this information in view state. We will store our
own information in the view state too. When we run the page and write my name in
the textbox and press the button, a postback occurs but my name still remains in
the textbox. Viewstate made that possible so after postback, the page looks like:

Now let us try to add our own information in the viewstate. Let's keep track of
users' postback on this page. Whenever user will hit a button, we will add 1 to the
stored pot back value. The way to do would be:
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack == true)
{
if (ViewState["number"] != null) //Lets retrieve, increase and store again
{
ViewState["number"] = Convert.ToInt32(ViewState["number"]) + 1;
}
else //First postback, lets store the info
{
ViewState["number"] = 1;
}
Label1.Text = ViewState["number"].ToString();
}
}
When we run the page and hit the button to do a postback, the web will show us the
postbacks being done so far which is being stored in viewstate:

View State is enabled by default, but we can disable it by setting the


EnableViewState property for each web control to false. This reduces the server
processing time and decreases page size.
Hidden Fields
ASP.NET allows you to store information in a HiddenField control, which renders as a
standard HTML hidden field. A hidden field does not render visibly in the browser,
but you can set its properties just as you can with a standard control. When a page
is submitted to the server, the content of a hidden field is sent in the HTTP form

82

collection along with the values of other controls. A hidden field acts as a repository
for any page-specific information that you want to store directly in the page.
In order for hidden-field values to be available during page processing, you must
submit the page using an HTTP POST command. If you use hidden fields and a page
is processed in response to a link or an HTTP GET command, the hidden fields will
not be available.
Example:
int newVal = Convert.ToInt32(HiddenField1.Value) + 1; //Hidden field default value
was 0
HiddenField1.Value = newVal.ToString();
Label2.Text = HiddenField1.Value;
Cookies
There are scenarios when we need to store the data between page requests. So far,
the techniques we have discussed store the data for the single page requests. Now
we look at the techniques that store information between page requests.
Cookies are small pieces of information that can be stored in a text file on users'
computer. The information can be accessed by the server and can be utilized to store
information that is required between page visits and between multiple visits on the
same page by the user. Let us do the same exercise of keeping track of postback by
using cookies.
Cookie Limitations
Most browsers support cookies of up to 4096 bytes. Because of this small limit,
cookies are best used to store small amounts of data, or better yet, an identifier
such as a user ID. The user ID can then be used to identify the user and read user
information from a database or other data store. Browsers also impose limitations on
how many cookies your site can store on the user's computer. Most browsers allow
only 20 cookies per site; if you try to store more, the oldest cookies are discarded.
Some browsers also put an absolute limit, usually 300, on the number of cookies
they will accept from all sites combined.
Types of Cookies
There are two types of cookies:
1. Non-persistent cookie
2. Persistent cookie
1. Non-persistent cookie: cookies are saved only while your web browser is
running. They can be used by a web server only until you close your browser.
They are not saved on your disk.
2. Persistent Cookie: cookies are stored on your computer hard disk. They stay
on your hard disk and can be accessed by web servers until they are deleted
or have expired.
To create a cookie:
HttpCookie c1 = new HttpCookie("myCookieName", "myCookieValue");
c1.Expires = System.DateTime.Today.AddMonths(12);

83

Response.Cookies.Add(c1);
To Read the cookie:
HttpCookie c2 = Request.Cookies["myCookieName"];
if (c2 != null)
Response.Write(c2.Value);
To view the cookie on the browser:
Firefox: go to tools -> page info -> security
IE: Tools -> Internet Options -> General -> Settings button under Browsing History
-> View Files
QueryString:
Web pages can be requested with query strings. The QueryString collection in
ASP.NET accesses this information. When you load file.html?x=y, it will parse the x
and the y for you.
Example:
First, we see an .aspx Web Forms page that executes when the user accesses
Default.aspx. The code here is the code-behind part, Default.aspx.cs, and it is
written in the C# programming language. To test the below code, run the page in
the web browser on the ASP.NET development server. It will be completely blank. Try
adding the string "?param=dotnet" at the end of the URL.
Code:
using System;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string v = Request.QueryString["param"];
if (v != null)
{
Response.Write("param is ");
Response.Write(v);
}
}
}
Output : It prints value of param query.
The screenshot shows the result.

84

Two query string parameters


To continue, we see how you can test two query string URL parameters. Another
common requirement is to test two different query strings. You may have to use
either one or both at once. The next example here has some inefficiencies, but it
works well otherwise.
using System;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string v = Request.QueryString["param"];
if (v != null)
{
Response.Write("param is ");
Response.Write(v);
}
string x = Request.QueryString["id"];
if (x != null)
{
Response.Write(" id detected");
}
}
}
Try the above example code by typing, at the end of the URL in Internet Explorer or
Firefox, the test url. The above string specifies that the "param" query is equal to
"first", while the "id" param is equal to "true".

85

Passing Value from one page to another


Example url with querystring can be something similar like this
http://yourdomainname.com/defauld.aspx?variable1=value1&variable2=value2
Suppose we have a textbox txtData and we want it's value on other page
than in code behind we would write in click event of btnGo.
private void btnGO_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.aspx?Value=" +txtData.Text);
}
Or
private void btnGO_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.aspx?city=" + txtData.Text
txtcountry.Text);
}

"&country="

Now to retrieve these values on other page we need to use request.querystring, we


can either retrieve them by variable name or by index
private void Page_Load(object sender,System.EventArgs e)
{
txtCity.Text = Request.QueryString["city"];
txtCountry.Text = Request.QueryString["country"];
}
Or we can also use
private void Page_Load(object sender,System.EventArgs e)
{
txtCity.Text = Request.QueryString[0];
86

txtCountry.Text = Request.QueryString[1];
}
QueryString can't be used for sending long data because it has a max lenght limit,
Data being transferred is visible in url of browser, and to use spaces and & in query
string we need to replace space by %20 and & by %26
private void btnGO_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.aspx?Value=" + txtData.Text.Replace(" ","%20");
}
Or we can use Server.UrlEncode method
private void btno_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.Aspx?" +"Name=" + Server.UrlEncode(txtData.Text));
}
Session:
When you are working with an application on your computer, you open it, do some
changes and then you close it. This is much like a Session. The computer knows who
you are. It knows when you open the application and when you close it. However, on
the internet there is one problem: the web server does not know who you are and
what you do, because the HTTP address doesn't maintain state.
ASP solves this problem by creating a unique cookie for each user. The cookie is sent
to the user's computer and it contains information that identifies the user. This
interface is called the Session object.
The Session object stores information about, or change settings for a user session.
Variables stored in a Session object hold information about one single user, and are
available to all pages in one application. Common information stored in session
variables are name, id, and preferences. The server creates a new Session object for
each new user, and destroys the Session object when the session expires.
A session starts when:
A new user requests an ASP file, and the Global.asa file includes a
Session_OnStart procedure
A value is stored in a Session variable
A user requests an ASP file, and the Global.asa file uses the <object> tag to
instantiate an object with session scope
When does a Session End?
A session ends if a user has not requested or refreshed a page in the application for
a specified period. By default, this is 20 minutes. If you want to set a timeout
interval that is shorter or longer than the default, use the Timeout property.
The proper way to create a session variable is:

87

Session["VarName"] = value;
Or you can use the Add method as:
Session.Add("VarName", value);
To remove an item from the session state:
Session.Remove("VarName");
To clear all items from the session state use:
Session.Clear();
Example 1:
Display last login time on the webpage.
Login page Code:
protected void btnLogin_click(object sender, EventArgs e)
{
Session["LoginTime"] = DateTime.Now;
}
Code of another page:
protected void Page_Load(object sender, EventArgs e)
{
Literal1.Text = "Last Online: " + ((DateTime)Session["LoginTime"]).ToString("yyyyMM-dd");
}
Example2:
1.Define an ASP.NET web site.
2.Create two pages within the site. The first page will contain an ASP.NET Web Form
that will post back to itself and then redirect to the second page.
Note: The reason this example uses two pages is to prove that a session variable is
available to a second, third, fourth, etc. page in the web site. Request variables,
which are an alternative to session variables, cannot be carried over from an
ASP.NET Web Form on one page to a second page
3.The first page must contain an ASP.NET Web Form that contains one
<asp:textbox> server control and an <asp:button> server control. The "id" attribute
of the textbox control should be set to "txtFirstName".
This code pulls the contents from the <asp:textbox> server control named
"txtFirstName" and creates a session variable named"sessFirstName" which is set
equal to the contents of the server control. In other words, this code creates a
session variable that holds the information the user enters on the form page.
code:
void Button1_Click(object sender, EventArgs e)
{
Session["sessFirstName"] = txtFirstName.Text;
Response.Redirect("session2.aspx");
}
4. In the second page enter the code below to write the session variable contents to
the page.
protected void Page_Load(object sender, EventArgs e)
{

88

Application:
Asp.NET Application State allows you to persist data across all users in the entire
application. Application variables can be used to store commonly used data such as
connection strings. For example:
Application("ConnectionString") = "connectionString"
This application variable can then be referenced later anywhere in the application:
SqlConnection conn = new SqlConnection(Application("ConnectionString")
Note however that application state is all cleared on an application restart (which
can be a server reboot, change to the web.config or when the application has no
current users). Thus you should place the application variable setups in the
Application_Start event of the Global.asax file.
The Global.asa file
The Global.asa file is an optional file that can contain declarations of objects,
variables, and methods that can be accessed by every page in an ASP application.
All valid browser scripts (JavaScript, VBScript, JScript, PerlScript, etc.) can be used
within Global.asa.
The Global.asa file can contain only the following:

Application events

Session events

<object> declarations

TypeLibrary declarations

the #include directive


Note: The Global.asa file must be stored in the root directory of the ASP application,
and each application can only have one Global.asa file.
Events in Global.asa
In Global.asa you can tell the application and session objects what to do when the
application/session starts and what to do when the application/session ends. The
code for this is placed in event handlers. The Global.asa file can contain four types of
events:
Application_OnStart - Occurs when the FIRST user calls the first page in an ASP
application. This event occurs after the Web server is restarted or after the
Global.asa file is edited. The "Session_OnStart" event occurs immediately after this
event.
Session_OnStart - This event occurs EVERY time a NEW user requests his or her
first page in the ASP application.
Session_OnEnd - This event occurs EVERY time a user ends a session. A usersession ends after a page has not been requested by the user for a specified time
(by default this is 20 minutes).
Application_OnEnd - This event occurs after the LAST user has ended the session.
Typically, this event occurs when a Web server stops. This procedure is used to clean
up settings after the Application stops, like delete records or write information to
text files.

89

A Global.asa file could look something like this:


<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>

90

Das könnte Ihnen auch gefallen