Index
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.
C# (Pronounced C sharp)
J# (Pronounced J sharp)
Development environments:
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.).
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.
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:
System.ComponentModel
System.Data
System.Drawing
System.Web
System.Web.SessionState
System.Web.UI
System.Web.UI.WebControls
System.Web.UI.HtmlControl
s
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;
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">
{
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
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
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
17
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
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.
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
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
Description
runat
Text
Description
24
CausesValidation
OnClientClick
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
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
25
NavigateUrl
Text
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
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
MaxLength
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
TextMode
Description
mode
27
ValidationGroup
Wrap
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
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
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
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
Text
TextAlign
On which side of the radio button the text should appear (right or left)
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
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
Caption
CaptionAlign
38
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>
<NavigateUrl>
<AlternateText
>
<Keyword>
Description
KeywordFilter
NavigateUrlField
40
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
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
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
Vertical Menu:
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
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" />
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
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
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
59
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
CreateUserUrl
DestinationPageUrl
DisplayRemeberMe
DisplayRemeberMe
60
property
sets
remember
me
functionality on or off.
Orientation
RememberMeSet
TextLayout
Description
RoleGroups
61
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
63
ChangePassword Control:
Description
CancelDestinationPageUrl:
SuccessPageUrl:
PasswordHintText:
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
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.
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.
68
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
72
73
74
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
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:
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
85
"&country="
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
89
90