Documente Academic
Documente Profesional
Documente Cultură
Net Notes
• Entries (RSS)
• Comments (RSS)
• Home
• .Net Framework
• Ado.Net
• Asp.Net
• C# .net
• C# Notes
• Java Script
• Project 2011
Asp.Net
ASP.NET State Management Overview
A new instance of the Web page class is created each time the page is posted to the server. In traditional Web
programmin
g, this would typically mean that all information associated with the page and the controls on the page would be lost with
each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip
from the browser or client device to the server.
To overcome this inherent limitation of traditional Web programming, ASP.NET includes several options that help you
preserve data on both a per-page basis and an application-wide basis. These features are as follows:
• View state
• Control state
• Hidden fields
• Cookies
• Query strings
• Application state
• Session state
• Profile Properties
View state, control state, hidden fields, cookies, and query strings all involve storing data on the client in various ways.
However, application state, session state, and profile properties all store data in memory on the server. Each option has
distinct advantages and disadvantages, depending on the scenario.
Client-Based State Management Options
The following sections describe options for state management that involve storing information either in the page or on the
client computer. For these options, no information is maintained on the server between round trips.View
StateThe ViewState property provides a dictionary object for retaining values between multiple requests for the same
page. This is the default method that the page uses to preserve page and control property values between round
trips.When the page is processed, the current state of the page and controls is hashed into a string and saved in the page
as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified
value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-
state string at page initialization and restores property information in the page.You can store values in view state as well.
For more information on using View State, see ASP.NET View State Overview. For recommendations about when you
should use view state, see ASP.NET State Management Recommendations.Control StateSometimes you need to store
control-state data in order for a control to work properly. For example, if you have written a custom control that has
different tabs that show different information, in order for that control to work as expected, the control needs to know
which tab is selected between round trips. The ViewState property can be used for this purpose, but view state can be
turned off at a page level by developers, effectively breaking your control. To solve this, the ASP.NET page framework
exposes a feature in ASP.NET called control state.The ControlState property allows you to persist property information that
is specific to a control and cannot be turned off like theViewState property.
Hidden Fields
ASP.NET allows you to store information in a HiddenField control, which renders as a standard HTML hidden field. A hidden
field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a
page is submitted to the server, the content of a hidden field is sent in the HTTP form 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.
Security Note
It is easy for a malicious user to see and modify the contents of a hidden field. Do not store any
information in a hidden field that is sensitive or that your application relies on to work properly.
For more information, seeASP.NET State Management Recommendations.
A HiddenField control stores a single variable in its Value property and must be explicitly added to the page. For more
information, see HiddenField Web Server Control Overview.
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. For usage recommendations, see ASP.NET State Management Recommendations.
Cookies
A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client
browser session. It contains site-specific information that the server sends to the client along with page output. Cookies
can be temporary (with specific expiration times and dates) or persistent.
You can use cookies to store information about a particular client, session, or application. The cookies are saved on the
client device, and when the browser requests a page, the client sends the information in the cookie along with the request
information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted)
indicating that the user has already been authenticated in your application.
Security Note
The browser can only send the data back to the server that originally created the cookie.
However, malicious users have ways to access cookies and read their contents. It is
recommended that you do not store sensitive information, such as a user name or password, in a
cookie. Instead, store a token in the cookie that identifies the user, and then use the token to look
up the sensitive information on the server.
For more information about using cookies, see Cookies and ASP.NET State Management Recommendations.
Query Strings
A query string is information that is appended to the end of a page URL. A typical query string might look like the following
example:
Copy
http://www.contoso.com/listwidgets.aspx?category=basic&price=100
In the URL path above, the query string starts with a question mark (?) and includes two attribute/value pairs, one called
“category” and the other called “price.”
Query strings provide a simple but limited way to maintain state information. For example, they are an easy way to pass
information from one page to another, such as passing a product number from one page to another page where it will be
processed. However, some browsers and client devices impose a 2083-character limit on the length of the URL.
Security Note
Information that is passed in a query string can be tampered with by a malicious user. Do not
rely on query strings to convey important or sensitive data. Additionally, a user can bookmark
the URL or send the URL to other users, thereby passing that information along with it. For more
information, see ASP.NET State Management Recommendations and How to: Protect Against
Script Exploits in a Web Application by Applying HTML Encoding to Strings.
In order for query string values to be available during page processing, you must submit the page using an HTTP GET
command. That is, you cannot take advantage of a query string if a page is processed in response to an HTTP POST
command. For usage recommendations, see ASP.NET State Management Recommendations.
Server-Based State Management Options
Once you add your application-specific information to application state, the server manages it. For usage
recommendations, see ASP.NET State Management Recommendations.
Session State
ASP.NET allows you to save values by using session state — which is an instance of the HttpSessionState class — for each
active Web-application session. For an overview, see ASP.NET Session State Overview.
Session state is similar to application state, except that it is scoped to the current browser session. If different users are
using your application, each user session will have a different session state. In addition, if a user leaves your application
and then returns later, the second user session will have a different session state from the first.
Session state is structured as a key/value dictionary for storing session-specific information that needs to be maintained
between server round trips and between requests for pages. For more information, see ASP.NET Session State Overview.
You can use session state to accomplish the following tasks:
• Uniquely identify browser or client-device requests and map them to an individual session instance on the server.
• Store session-specific data on the server for use across multiple browser or client-device requests within the same session.
• Raise appropriate session management events. In addition, you can write application code leveraging these events.
Once you add your application-specific information to session state, the server manages this object. Depending on which
options you specify, session information can be stored in cookies, on an out-of-process server, or on a computer running
Microsoft SQL Server. For usage recommendations, see ASP.NET State Management Recommendations.
Profile Properties
ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to
session state, except that the profile data is not lost when a user’s session expires. The profile-properties feature uses an
ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows
you to easily manage user information without requiring you to create and maintain your own database. In addition, the
profile makes the user information available using a strongly typed API that you can access from anywhere in your
application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system
that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner.
To use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you
to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a
custom format and to a custom storage mechanism such as an XML file, or even to a web service.
Because data that is placed in profile properties is not stored in application memory, it is preserved through Internet
Information Services (IIS) restarts and worker-process restarts without losing data. Additionally, profile properties can be
persisted across multiple processes such as in a Web farm or a Web garden. For more information, see ASP.NET Profile
Properties Overview.
ASP.NET State Management Recommendations
State management is the process by which you maintain state and page information over multiple requests for the same or
different pages. As is true for any HTTP-based technology, Web Forms pages are stateless, which means that they do not
automatically indicate whether the requests in a sequence are all from the same client or even whether a single browser
instance is still actively viewing a page or site. Furthermore, pages are destroyed and re-created with each round trip to
the server; therefore, page information will not exist beyond the life cycle of a single page. For more information about
server round trips and the life cycle of Web Forms pages, see ASP.NET Page Life Cycle Overview.
ASP.NET provides multiple ways to maintain state between server round trips. Which of these options you choose depends
heavily upon your application, and it should be based on the following criteria:
• How much information do you need to store?
• Does the client accept persistent or in-memory cookies?
• Do you want to store the information on the client or on the server?
• Is the information sensitive?
• What performance and bandwidth criteria do you have for your application?
• What are the capabilities of the browsers and devices that you are targeting?
• Do you need to store information per user?
• How long do you need to store the information?
• Do you have a Web farm (multiple servers), a Web garden (multiple processes on one machine), or a single process that
serves the application?
Client-Side State Management Options
Storing page information using client-side options doesn’t use server resources. These options typically have minimal
security but fast server performance because the demand on server resources is modest. However, because you must
send information to the client for it to be stored, there is a practical limit on how much information you can store this
way.The following are the client-side state management options that ASP.NET supports:
• View state
• Control state
• Hidden fields
• Cookies
• Query strings
View State
Web Forms pages provide the ViewState property as a built-in structure for automatically retaining values between
multiple requests for the same page. View state is maintained as a hidden field in the page. For more information,
see ASP.NET State Management Overview.
You can use view state to store your own page-specific values across round trips when the page posts back to itself. For
example, if your application is maintaining user-specific information — that is, information that is used in the page but is
not necessarily part of any control — you can store it in view state.
Advantages of using view state are:
• No server resources are required The view state is contained in a structure within the page code.
• Simple implementation View state does not require any custom programming to use. It is on by default to maintain
state data on controls.
• Enhanced security features The values in view state are hashed, compressed, and encoded for Unicode
implementations, which provides more security than using hidden fields.
Disadvantages of using view state are:
• Performance considerations Because the view state is stored in the page itself, storing large values can cause the
page to slow down when users display it and when they post it. This is especially relevant for mobile devices, where
bandwidth is often a limitation.
• Device limitations Mobile devices might not have the memory capacity to store a large amount of view-state data.
• Potential security risks The view state is stored in one or more hidden fields on the page. Although view state stores
data in a hashed format, it can still be tampered with. The information in the hidden field can be seen if the page output
source is viewed directly, creating a potential security issue. For more information, see ASP.NET Web Application
Security and Basic Security Practices for Web Applications.
For more information about using view state, see View State Overview.
Control State
The ASP.NET page framework provides the ControlState property as way to store custom control data between server
trips. For example, if you have written a custom control that has different tabs showing different information, in order for
that control to work as expected, the control needs to know which tab is selected between round trips. View state can be
used for this purpose, but developers can turn view state off at the page level, effectively breaking your control. Unlike
view state, control state cannot be turned off, so it provides a more reliable way to store control-state data.
Advantages of using control state are:
• No server resources are required By default, control state is stored in hidden fields on the page.
• Reliability Because control state cannot be turned off like view state, control state is a more reliable method for
managing the state of controls.
• Versatility Custom adapters can be written to control how and where control-state data is stored.
Disadvantage of using control state are:
• Some programming is required While the ASP.NET page framework provides a foundation for control state, control
state is a custom state-persistence mechanism. To fully utilize control state, you must write code to save and load control
state.
Hidden Fields
You can store page-specific information in a hidden field on your page as a way of maintaining the state of your page.
If you use hidden fields, it is best to store only small amounts of frequently changed data on the client.
Note
If you use hidden fields, you must submit your pages to the server using the HTTP POST method
rather than requesting the page via the page URL (the HTTP GET method).
Advantages of using hidden fields are:
• No server resources are required The hidden field is stored and read from the page.
• Widespread support Almost all browsers and client devices support forms with hidden fields.
• Simple implementation Hidden fields are standard HTML controls that require no complex programming logic.
Disadvantages of using hidden fields are:
• Potential security risks The hidden field can be tampered with. The information in the hidden field can be seen if the
page output source is viewed directly, creating a potential security issue. You can manually encrypt and decrypt the
contents of a hidden field, but doing so requires extra coding and overhead. If security is a concern, consider using a
server-based state mechanism so that no sensitive information is sent to the client. For more information, see ASP.NET
Web Application Security and Basic Security Practices for Web Applications.
• Simple storage architecture The hidden field does not support rich data types. Hidden fields offer a single string value
field in which to place information. To store multiple values, you must implement delimited strings and the code to parse
those strings. You can manually serialize and de-serialize rich data types to and from hidden fields, respectively. However,
it requires extra code to do so. If you need to store rich data types on the client, consider using view state instead. View
state has serialization built-in, and it stores data in hidden fields.
• Performance considerations Because hidden fields are stored in the page itself, storing large values can cause the
page to slow down when users display it and when they post it.
• Storage limitations If the amount of data in a hidden field becomes very large, some proxies and firewalls will prevent
access to the page that contains them. Because the maximum amount can vary with different firewall and proxy
implementations, large hidden fields can be sporadically problematic. If you need to store many items of data, consider
doing one of the following:
○ Put each item in a separate hidden field.
○ Use view state with view-state chunking turned on, which automatically separates data into multiple hidden fields.
○ Instead of storing data on the client, persist the data on the server. The more data you send to the client, the slower the
apparent response time of your application will be because the browser will need to download or send more data.
Cookies
Cookies are useful for storing small amounts of frequently changed information on the client. The information is sent with
the request to the server. For details about creating and reading cookies, see ASP.NET Cookies Overview.
Advantages of using cookies are:
• Configurable expiration rules The cookie can expire when the browser session ends, or it can exist indefinitely on the
client computer, subject to the expiration rules on the client.
• No server resources are required The cookie is stored on the client and read by the server after a post.
• Simplicity The cookie is a lightweight, text-based structure with simple key-value pairs.
• Data persistence Although the durability of the cookie on a client computer is subject to cookie expiration processes on
the client and user intervention, cookies are generally the most durable form of data persistence on the client.
Disadvantages of using cookies are:
• Size limitations Most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies
is becoming more common in newer browser and client-device versions.
• User-configured refusal Some users disable their browser or client device’s ability to receive cookies, thereby limiting
this functionality.
• Potential security risks Cookies are subject to tampering. Users can manipulate cookies on their computer, which can
potentially cause a security risk or cause the application that is dependent on the cookie to fail. Also, although cookies are
only accessible by the domain that sent them to the client, hackers have historically found ways to access cookies from
other domains on a user’s computer. You can manually encrypt and decrypt cookies, but it requires extra coding and can
affect application performance because of the time that is required for encryption and decryption. For more information,
see ASP.NET Web Application Security and Basic Security Practices for Web Applications.
Note
Cookies are often used for personalization, where content is customized for a known user. In
most of these cases, identification is the issue rather than authentication. Thus, you can typically
secure a cookie that is used for identification by storing the user name, account name, or a
unique user ID (such as a GUID) in the cookie and then using the cookie to access the user
personalization infrastructure of a site.
Query Strings
A query string is information that is appended to the end of a page URL. For more information, see ASP.NET State
Management Overview.
You can use a query string to submit data back to your page or to another page through the URL. Query strings provide a
simple but limited way of maintaining some state information. For example, query strings are an easy way to pass
information from one page to another, such as passing a product number to another page where it will be processed.
Advantages of using query strings are:
• No server resources are required The query string is contained in the HTTP request for a specific URL.
• Widespread support Almost all browsers and client devices support using query strings to pass values.
• Simple implementation ASP.NET provides full support for the query-string method, including methods of reading query
strings using the Paramsproperty of the HttpRequest object.
Disadvantages of using query strings are:
• Potential security risks The information in the query string is directly visible to the user via the browser’s user
interface. A user can bookmark the URL or send the URL to other users, thereby passing the information in the query
string along with it. If you are concerned about any sensitive data in the query string, consider using hidden fields in a
form that uses POST instead of using query strings. For more information, see ASP.NET Web Application Security and Basic
Security Practices for Web Applications.
• Limited capacity Some browsers and client devices impose a 2083-character limit on the length of URLs.
Client-Side Method State Management Summary
The following table lists the client-side state management options that are available with ASP.NET, and provides
recommendations about when you should use each option.
State Recommended usage
management
option
View state Use when you need to store small amounts of information for a page that will
post back to itself. Using the ViewStateproperty provides functionality with
basic security.
Control state Use when you need to store small amounts of state information for a control
between round trips to the server.
Hidden fields Use when you need to store small amounts of information for a page that will
post back to itself or to another page, and when security is not an issue.NoteYou
can use a hidden field only on pages that are submitted to the server.
Cookies Use when you need to store small amounts of information on the client and
security is not an issue.
Query string Use when you are transferring small amounts of information from one page to
another and security is not an issue.NoteYou can use query strings only if you
are requesting the same page, or another page via a link.
Server-Side State Management Options
• Application state
• Session state
• Profile properties
• Database support
Application State
ASP.NET provides application state via the HttpApplicationState class as a method of storing global application-specific
information that is visible to the entire application. Application-state variables are, in effect, global variables for an
ASP.NET application. For more information, see ASP.NET Application State Overview
You can store your application-specific values in application state, which is then managed by the server. For more
information, see ASP.NET State Management Overview.
Data that is shared by multiple sessions and does not change often is the ideal type of data to insert into application-state
variables.
Advantages of using application state are:
• Simple implementation Application state is easy to use, familiar to ASP developers, and consistent with other .NET
Framework classes.
• Application scope Because application state is accessible to all pages in an application, storing information in
application state can mean keeping only a single copy of the information (for instance, as opposed to keeping copies of
information in session state or in individual pages).
Disadvantages of using application state are:
• Application scope The scope of application state can also be a disadvantage. Variables stored in application state are
global only to the particular process the application is running in, and each application process can have different values.
Therefore, you cannot rely on application state to store unique values or update global counters in Web-garden and Web-
farm server configurations.
• Limited durability of data Because global data that is stored in application state is volatile, it will be lost if the Web
server process containing it is destroyed, such as from a server crash, upgrade, or shutdown.
• Resource requirements Application state requires server memory, which can affect the performance of the server as
well as the scalability of the application.
Careful design and implementation of application state can increase Web application performance. For example, placing a
commonly used, relatively static dataset in application state can increase site performance by reducing the overall number
of data requests to a database. However, there is a performance trade-off. Application state variables containing large
blocks of information reduce Web server performance as server load increases. The memory occupied by a variable stored
in application state is not released until the value is either removed or replaced. Therefore, it is best to use application-
state variables only with small, infrequently changed datasets. For more information, see ASP.NET Performance Overview.
Session State
ASP.NET provides a session state, which is available as theHttpSessionState class, as a method of storing session-specific
information that is visible only within the session. ASP.NET session state identifies requests from the same browser during
a limited time window as a session, and provides the ability to persist variable values for the duration of that session. For
more information, see ASP.NET State Management Overviewand ASP.NET Session State Overview.
You can store your session-specific values and objects in session state, which is then managed by the server and available
to the browser or client device. The ideal data to store in session-state variables is short-lived, sensitive data that is
specific to an individual session.
Advantages of using session state are:
• Simple implementation The session-state facility is easy to use, familiar to ASP developers, and consistent with
other .NET Framework classes.
• Session-specific events Session management events can be raised and used by your application.
• Data persistence Data placed in session-state variables can be preserved through Internet Information Services (IIS)
restarts and worker-process restarts without losing session data because the data is stored in another process space.
Additionally, session-state data can be persisted across multiple processes, such as in a Web farm or a Web garden.
• Platform scalability Session state can be used in both multi-computer and multi-process configurations, therefore
optimizing scalability scenarios.
• Cookieless support Session state works with browsers that do not support HTTP cookies, although session state is most
commonly used with cookies to provide user identification facilities to a Web application. Using session state without
cookies, however, requires that the session identifier be placed in the query string, which is subject to the security issues
stated in the query string section of this topic. For more information about using session state without cookies,
see ASP.NET Web Site Administration.
• Extensibility You can customize and extend session state by writing your own session-state provider. Session state data
can then be stored in a custom data format in a variety of data storage mechanisms, such as a database, an XML file, or
even to a Web service. For more information, seeImplementing a Session-State Store Provider.
Disadvantage of using session state are:
• Performance considerations Session-state variables stay in memory until they are either removed or replaced, and
therefore can degrade server performance. Session-state variables that contain blocks of information, such as large
datasets, can adversely affect Web-server performance as server load increases.
Profile Properties
ASP.NET provides a feature called profile properties, which allows you to store user-specific data. It is similar to session
state, except that unlike session state, the profile data is not lost when a user’s session expires. The profile properties
feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET
profile allows you to easily manage user information without requiring you to create and maintain your own database. In
addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in
your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage
system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe
manner. For more information, see ASP.NET Profile Properties Overview.
Advantages of using profile properties are:
• Data persistence Data placed in profile properties is preserved through IIS restarts and worker-process restarts without
losing data because the data is stored in an external mechanism. Additionally, profile properties can be persisted across
multiple processes, such as in a Web farm or a Web garden.
• Platform scalability Profile properties can be used in both multi-computer and multi-process configurations, therefore
optimizing scalability scenarios.
• Extensibility In order to use profile properties, you must configure a profile provider. ASP.NET includes
a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile
provider class that stores profile data in a custom format and to a custom storage mechanism, such as an XML file, or
even to a Web service. For more information, see ASP.NET Profile Providers and Implementing a Profile Provider.
Disadvantages of using profile properties are:
• Performance considerations Profile properties are generally slower than using session state because instead of storing
data in memory, the data is persisted to a data store.
• Additional configuration requirements Unlike session state, the profile properties feature requires a considerable
amount of configuration to use. To use profile properties, you must not only configure a profile provider, but you must pre-
configure all of the profile properties that you want to store. For more information, see ASP.NET Profile Properties
Overview and Defining ASP.NET Profile Properties.
• Data maintenance Profile properties require a certain amount of maintenance. Because profile data is persisted to non-
volatile storage, you must make sure that your application calls the appropriate cleanup mechanisms, which are provided
by the profile provider, when data becomes stale.
Database Support
In some cases, you might want to use database support to maintain state on your Web site. Typically, database support is
used in conjunction with cookies or session state. For example, it is common for an e-commerce Web site to maintain state
information by using a relational database for the following reasons:
• Security
• Personalization
• Consistency
• Data mining
The following are typical features of a cookie-supported database Web site:
• Security The visitor types an account name and password into a site logon page. The site infrastructure queries the
database with the logon values to determine whether the user has rights to utilize your site. If the database validates the
user information, the Web site will distribute a valid cookie containing a unique ID for that user on that client computer.
The site grants access to the user.
• Personalization With security information in place, your site can distinguish each user by reading the cookie on the
client computer. Typically, sites have information in the database that describes the preferences of a user (identified by a
unique ID). This relationship is known as personalization. The site can research the user’s preferences using the unique ID
contained in the cookie, and then place content and information in front of the user that pertains to the user’s specific
wishes, reacting to the user’s preferences over time.
• Consistency If you have created a commerce Web site, you might want to keep transactional records of purchases
made for goods and services on your site. This information can be reliably saved in your database and referenced by the
user’s unique ID. It can be used to determine whether a purchase transaction has been completed, and to determine the
course of action if a purchase transaction fails. The information can also be used to inform the user of the status of an
order placed using your site.
• Data mining Information about your site usage, your visitors, or your product transactions can be reliably stored in a
database. For example, your business development department might want to use the data collected from your site to
determine next year’s product line or distribution policy. Your marketing department might want to examine demographic
information about users on your site. Your engineering and support departments might want to look at transactions and
note areas where your purchasing process could be improved. Most enterprise-level relational databases, such as Microsoft
SQL Server, contain an expansive toolset for most data mining projects.
By designing the Web site to repeatedly query the database by using the unique ID during each general stage in the above
scenario, the site maintains state. In this way, the user perceives that the site is remembering and reacting to him or her
personally.
Advantages of using a database to maintain state are:
• Security Access to databases requires rigorous authentication and authorization.
• Storage capacity You can store as much information as you like in a database.
• Data persistence Database information can be stored as long as you like, and it is not subject to the availability of the
Web server.
• Robustness and data integrity Databases include various facilities for maintaining good data, including triggers and
referential integrity, transactions, and so on. By keeping information about transactions in a database (rather than in
session state, for example), you can recover from errors more readily.
• Accessibility The data stored in your database is accessible to a wide variety of information-processing tools.
• Widespread support There is a large range of database tools available, and many custom configurations are available.
Disadvantages of using a database to maintain state are:
• Complexity Using a database to support state management requires that the hardware and software configurations be
more complex.
• Performance considerations Poor construction of the relational data model can lead to scalability issues. Also,
leveraging too many queries to the database can adversely affect server performance.
Server-Side Method State Management Summary
The following table lists the server-side state management options that are available with ASP.NET, and provides
recommendations about when you should use each option.
State Recommended usage
management
option
Application Use when you are storing infrequently changed, global information that is used
state by many users, and security is not an issue. Do not store large quantities of
information in application state.
Session state Use when you are storing short-lived information that is specific to an individual
session and security is an issue. Do not store large quantities of information in
session state. Be aware that a session-state object will be created and maintained
for the lifetime of every session in your application. In applications hosting many
users, this can occupy significant server resources and affect scalability.
Profile Use when you are storing user-specific information that needs to be persisted
properties after the user session is expired and needs to be retrieved again on subsequent
visits to your application.
Database Use when you are storing large amounts of information, managing transactions,
support or the information must survive application and session restarts. Data mining is a
concern, and security is an issue.
.NET Framework 4 – ASP.NET
ASP.NET Cookies Overview
A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The
cookie contains information the Web application can read whenever the user visits the site.
A Visual Studio project with source code is available to accompany this topic:Download.
This topic contains the following:
• Scenarios
• Background
• Code Examples
• Class Reference
• Additional Resources
• What’s New
Scenarios
Cookies provide a means in Web applications to store user-specific information. For example, when a user visits your site,
you can use cookies to store user preferences or other information. When the user visits your Web site another time, the
application can retrieve the information it stored earlier.Back to topBackground
A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The
cookie contains information the Web application can read whenever the user visits the site.For example, if a user requests
a page from your site and your application sends not just a page, but also a cookie containing the date and time, when the
user’s browser gets the page, the browser also gets the cookie, which it stores in a folder on the user’s hard disk.Later, if
user requests a page from your site again, when the user enters the URL the browser looks on the local hard disk for a
cookie associated with the URL. If the cookie exists, the browser sends the cookie to your site along with the page request.
Your application can then determine the date and time that the user last visited the site. You might use the information to
display a message to the user or check an expiration date.Cookies are associated with a Web site, not with a specific page,
so the browser and server will exchange cookie information no matter what page the user requests from your site. As the
user visits different sites, each site might send a cookie to the user’s browser as well; the browser stores all the cookies
separately.Cookies help Web sites store information about visitors. More generally, cookies are one way of maintaining
continuity in a Web application—that is, of performing state management. Except for the brief time when they are actually
exchanging information, the browser and Web server are disconnected. Each request a user makes to a Web server is
treated independently of any other request. Many times, however, it’s useful for the Web server to recognize users when
they request a page. For example, the Web server on a shopping site keeps track of individual shoppers so the site can
manage shopping carts and other user-specific information. A cookie therefore acts as a kind of calling card, presenting
pertinent identification that helps an application know how to proceed.Cookies are used for many purposes, all relating to
helping the Web site remember users. For example, a site conducting a poll might use a cookie simply as a Boolean value
to indicate whether a user’s browser has already participated in voting so that the user cannot vote twice. A site that asks
a user to log on might use a cookie to record that the user already logged on so that the user does not have to keep
entering credentials.
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. (See the section “Cookies and Security” below for information about
security implications of storing user information.)
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.
A cookie limitation that you might encounter is that users can set their browser to refuse cookies. If you define a P3P
privacy policy and place it in the root of your Web site, more browsers will accept cookies from your site. However, you
might have to avoid cookies altogether and use a different mechanism to store user-specific information. A common
method for storing user information is session state, but session state depends on cookies, as explained later in the section
“Cookies and Session State.”
Note
For more information on state management and options for saving information in a Web
application, see ASP.NET State Management Overviewand ASP.NET State Management
Recommendations.
Although cookies can be very useful in your application, the application should not depend on being able to store cookies.
Do not use cookies to support critical features. If your application must rely on cookies, you can test to see whether the
browser will accept cookies. See the “Checking Whether a Browser Accepts Cookies” section later in this topic.
Writing Cookies
The browser is responsible for managing cookies on a user system. Cookies are sent to the browser via
the HttpResponse object that exposes a collection called Cookies. You can access the HttpResponse object as
theResponse property of your Page class. Any cookies that you want to send to the browser must be added to this
collection. When creating a cookie, you specify a Name and Value. Each cookie must have a unique name so that it can be
identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will
cause one to be overwritten.
You can also set a cookie’s date and time expiration. Expired cookies are deleted by the browser when a user visits the site
that wrote the cookies. The expiration of a cookie should be set for as long as your application considers the cookie value
to be valid. For a cookie to effectively never expire, you can set the expiration date to be 50 years from now.
Note
Users can clear the cookies on their computer at any time. Even if you store cookies with long
expiration times, a user might decide to delete all cookies, wiping out any settings you might
have stored in cookies.
If you do not set the cookie’s expiration, the cookie is created but it is not stored on the user’s hard disk. Instead, the
cookie is maintained as part of the user’s session information. When the user closes the browser, the cookie is discarded.
A non-persistent cookie like this is useful for information that needs to be stored for only a short time or that for security
reasons should not be written to disk on the client computer. For example, non-persistent cookies are useful if the user is
working on a public computer, where you do not want to write the cookie to disk.
You can add cookies to the Cookies collection in a number of ways. The following example shows two methods to write
cookies:
VB
C#
C++
F#
JScript
Copy
Response.Cookies["userName"].Value = “patrick”;
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie(“lastVisit”);
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
The example adds two cookies to the Cookies collection, one named userName and the other named lastVisit. For the first
cookie, the values of the Cookies collection are set directly. You can add values to the collection this way
because Cookies derives from a specialized collection of typeNameObjectCollectionBase.
For the second cookie, the code creates an instance of an object of typeHttpCookie, sets its properties, and then adds it to
the Cookies collection via the Add method. When you instantiate an HttpCookie object, you must pass the cookie name as
part of the constructor.
Both examples accomplish the same task, writing a cookie to the browser. In both methods, the expiration value must be
of type DateTime. However, the lastVisited value is also a date-time value. Because all cookie values are stored as strings,
the date-time value has to be converted to a String .
Cookies with More Than One Value
You can store one value in a cookie, such as user name and last visit. You can also store multiple name-value pairs in a
single cookie. The name-value pairs are referred to as subkeys. (Subkeys are laid out much like a query string in a URL.)
For example, instead of creating two separate cookies named userName and lastVisit, you can create a single cookie
named userInfo that has the subkeys userName and lastVisit.
You might use subkeys for several reasons. First, it is convenient to put related or similar information into a single cookie.
In addition, because all the information is in a single cookie, cookie attributes such as expiration apply to all the
information. (Conversely, if you want to assign different expiration dates to different types of information, you should store
the information in separate cookies.)
A cookie with subkeys also helps you limit the size of cookie files. As noted earlier in the “Cookie Limitations” section,
cookies are usually limited to 4096 bytes and you can’t store more than 20 cookies per site. By using a single cookie with
subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50
characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which
counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the
separate cookies and can save around 200 bytes.
To create a cookie with subkeys, you can use a variation of the syntax for writing a single cookie. The following example
shows two ways to write the same cookie, each with two subkeys:
VB
C#
C++
F#
JScript
Copy
Response.Cookies["userInfo"]["userName"] = “patrick”;
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie(“userInfo”);
aCookie.Values["userName"] = “patrick”;
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
Controlling Cookie Scope
By default, all cookies for a site are stored together on the client, and all cookies are sent to the server with any request to
that site. In other words, every page in a site gets all of the cookies for that site. However, you can set the scope of
cookies in two ways:
• Limit the scope of cookies to a folder on the server, which allows you to limit cookies to an application on the site.
• Set scope to a domain, which allows you to specify which subdomains in a domain can access a cookie.
Limiting Cookies to a Folder or Application
To limit cookies to a folder on the server, set the cookie’s Path property, as in the following example:
VB
C#
C++
F#
JScript
Copy
HttpCookie appCookie = new HttpCookie(“AppCookie”);
appCookie.Value = “written ” + DateTime.Now.ToString();
appCookie.Expires = DateTime.Now.AddDays(1);
appCookie.Path = “/Application1″;
Response.Cookies.Add(appCookie);
Note
You can also write cookies by adding them to the Cookies collection directly as shown in earlier
examples.
The path can either be a physical path under the site root or a virtual root. The effect will be that the cookie is available
only to pages in the Application1 folder or virtual root. For example, if your site is called www.contoso.com, the cookie
created in the previous example will be available to pages with the path http://www.contoso.com/Application1/ and to any
pages beneath that folder. However, the cookie will not be available to pages in other applications such as
http://www.contoso.com/Application2/ or just http://www.contoso.com/.
Note
In some browsers, the path is case sensitive. You cannot control how users type URLs into their
browsers, but if your application depends on cookies tied to a specific path, be sure that the
URLs in any hyperlinks you create match the case of the Path property value.
Control State
In addition to view state, ASP.NET supports control state. The page uses control state to persist control information that
must be retained between postbacks, even if view state is disabled for the page or for a control. Like view state, control
state is stored in one or more hidden fields.
Saving Values in View State
You can access view state information by using the page’s ViewStateproperty, which exposes a dictionary object. You can
use this dictionary to store custom values. A typical use is to store the value of custom properties that you define in the
page.
Because view state is sent as a hidden field, you can make changes to view state until the
page’s PreRenderComplete event. After the page is rendered to the browser, changes to view state will not be saved.
The information in the hidden view state field can be seen by users if they view the source of the Web page and can
decode base-64 encoded strings. This creates a potential security issue. For more information about security issues with
view state, see Securing View State later in this topic.
Note
To use the ViewState property, the ASP.NET Web page must have a form element that has the
attribute runat=”server”.
To save a value to view state, create a new item that contains the value to save and add the item to the view state
dictionary. The following example shows an ASP.NET Web page with code that saves a string and an integer value in view
state.
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd”>
<script runat=”server”>
// Sample ArrayList for the page.
ArrayList PageArrayList;
ArrayList CreateArray()
{
// Create a sample ArrayList.
ArrayList result = new ArrayList(4);
result.Add(“item 1″);
result.Add(“item 2″);
result.Add(“item 3″);
result.Add(“item 4″);
return result;
}
void Page_Load(object sender, EventArgs e)
{
if (ViewState["arrayListInViewState"] != null)
{
PageArrayList = (ArrayList)ViewState["arrayListInViewState"];
}
else
{
// ArrayList isn’t in view state, so it must be created and populated.
PageArrayList = CreateArray();
}
// Code that uses PageArrayList.
}
void Page_PreRender(object sender, EventArgs e)
{
// Save PageArrayList before the page is rendered.
ViewState.Add(“arrayListInViewState”, PageArrayList);
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>View state sample</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
</div>
</form>
</body>
</html>
Data Types You Can Store in View State
You can store objects of the following types in view state:
• Strings
• Integers
• Boolean values
• Array objects
• ArrayList objects
• Hash tables
• Custom type converters (see the TypeConverter class for more information)
You can store other types of data also, but the class must be compiled with the Serializable attribute so that its values can
be serialized for view state.
Reading Values from View State
To read a value from view state, you get the ViewState property of page and then read the value from the view state
dictionary.
The following example shows how you can get an ArrayList object named arrayListInViewState from view state and then
bind a GridView control to the object as a data source.
arrayList = new ArrayList();
arrayList = (ArrayList)ViewState["arrayListInViewState"];
this.GridView1.DataSource = arrayList;
this.GridView1.DataBind();
Values in view state are typed as String. In Visual Basic, if you set Option Strict On, you must cast view state values to the
appropriate type before you use them, as shown in the previous example. In C#, you must always cast to the appropriate
type when you read view state values.
If you try to get a value out of view state that does not exist, no exception is thrown. To make sure that a value is in view
state, check first whether the object exists. The following example shows how to check for a view state entry.
if (ViewState["color"] == null)
// No such value in view state, take appropriate action.
If you try to use a nonexistent view state entry in some other way (for example, to examine its type),
a NullReferenceException exception is thrown.
Back to top
Securing View State
By default, view state data is stored in the page in a hidden field and is encoded using base64 encoding. In addition, a
hash of the view state data is created from the data by using a machine authentication code (MAC) key. The hash value is
added to the encoded view state data and the resulting string is stored in the page. When the page is posted back to the
server, the ASP.NET page framework re-computes the hash value and compares it with the value stored in view state. If
the hash values do not match, an exception is raised that indicates that view state data might be invalid.
By creating a hash value, the ASP.NET page framework can test whether the view state data has been corrupted or
tampered with. However, even if it is not tampered with, view state data can still be intercepted and read by malicious
users.
Usign the MAC for Computing the View State Hash Value
The MAC key that is used to compute the view state hash value is either auto-generated or specified in the Machine.config
file. If the key is auto-generated, it is created based on the MAC address of the computer, which is the unique GUID value
of the network adapter in that computer.
It can be difficult for malicious users to reverse-engineer the MAC key based on the hash value in view state. Thus, MAC
encoding is a reasonably reliable way to determine whether view state data has been changed.
In general, the larger the MAC key that is used to generate the hash, the less likely it is that the hash value for different
strings will be the same. When the key is auto-generated, ASP.NET uses SHA-1 encoding to create a large key. However,
in a Web-farm environment, the key must be the same across all the servers. If the key is not the same, and the page is
posted back to a different server than the one that created the page, the ASP.NET page framework will raise an exception.
Therefore, in a Web farm environment, you should specify a key in the Machine.config file instead of letting ASP.NET auto-
generate one. In that case, make sure that you create a key that is long enough to offer sufficient security for the hashed
value. However, the longer the key is, the more time it takes to create a hash. Therefore, you must weigh security needs
versus performance needs.
Encrypting View State
Although MAC encoding helps prevent tampering with view state data, it does not prevent users from viewing the data.
You can prevent people from viewing this data in two ways: by transmitting the page over SSL, and by encrypting the view
state data. Requiring the page to be sent over SSL can help prevent data-packet sniffing and unauthorized data access by
people who are not the intended recipients of the page.
However, the user who requested the page can still view the view state data because SSL decrypts the page to display it in
the browser. This is fine if you are not concerned about authorized users having access to view state data. However, in
some cases, controls might use view state to store information that no users should have access to. For example, the page
might contain a data-bound control that stores item identifiers (data keys) in view state. If those identifiers contain
sensitive data, such as customer IDs, you should encrypt the view state data in addition to or instead of sending the page
over SSL.
To encrypt the data, set the page’s ViewStateEncryptionMode property to true. If you store information in view state, you
can use regular read and write techniques; the page handles all encryption and decryption for you. Encrypting view state
data can affect the performance of your application. Therefore, do not use encryption unless you need it.
Control State Encryption
Controls that use control state can require that view state be encrypted by calling
the RegisterRequiresViewStateEncryption method. If any control in the page requires that view state be encrypted, all view
state in the page will be encrypted.
Per-user View State Encoding
If a Web site authenticates users, you can set the ViewStateUserKeyproperty in the Page_Init event handler to associate
the page’s view state with a specific user. This helps prevent one-click attacks, in which a malicious user creates a valid,
pre-filled Web page with view state from a previously created page. The attacker then lures a victim into clicking a link
that sends the page to the server by using the victim’s identity.
When the ViewStateUserKey property is set, the attacker’s identity is used to create the hash of the view state of the
original page. When the victim is lured into resending the page, the hash values will be different because the user keys are
different. The page will fail verification and an exception will be thrown.
You must associate the ViewStateUserKey property with a unique value for each user, such as the user name or identifier.
Securing Configuration in Shared Hosting Environment
In a shared hosting environment, malicious users can potentially modify state-management properties that might affect
other applications on the computer. This can be done through direct modification of the Machine.config file, modification by
way of the configuration classes, and other administration and configuration tools. You can help prevent modification to
your application configuration by encrypting sections of configuration files. For more information, see Encrypting
Configuration Information Using Protected Configuration
Class Reference
ViewState Provides a dictionary object for retaining values between requests for the same
page.
PageStatePersisterProvides a means to define a custom mechanism for storing view state
information, such as in a SQL Server database.
ASP.NET Session State Overview
Use ASP.NET session state to store and retrieve values for a user.
This topic contains:
• Background
• Code Examples
• Class Reference
A Visual Studio project with source code is available to accompany this topic: Download.
Background
ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web
application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an
independent request. The server retains no knowledge of variable values that were used during previous requests.
ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides
a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all
ASP.NET applications.Alternatives to session state include the following:
• Application state, which stores variables that can be accessed by all users of an ASP.NET application.
• Profile properties, which persists user values in a data store without expiring them.
• ASP.NET caching, which stores values in memory that is available to all ASP.NET applications.
• View state, which persists values in a page.
• Cookies.
• The query string and fields on an HTML form that are available from an HTTP request.
For a comparison of different state-management options, see ASP.NET State Management Recommendations.
Session Variables
Session variables are stored in a SessionStateItemCollection object that is exposed through
the HttpContext.Session property. In an ASP.NET page, the current session variables are exposed through the Session
property of the Page object.
The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are
created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to
the collection. The following example shows how to create session variables in an ASP.NET page for the first and last name
of a user, and set them to values retrieved from TextBox controls.
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;
Session variables can be any valid .NET Framework type. The following example stores an ArrayList object in a session
variable named StockPicks. The value returned by the StockPicks session variable must be cast to the appropriate type
when you retrieve it from the SessionStateItemCollection.
// When retrieving an object from session state, cast it to
// the appropriate type.
ArrayList stockPicks = (ArrayList)Session["StockPicks"];
// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;
Note
When you use a session-state mode other than InProc, the session-variable type must be either a
primitive .NET type or serializable. This is because the session-variable value is stored in an
external data store. For more information, see Session-State Modes.
Session Identifiers
Sessions are identified by a unique identifier that can be read by using theSessionID property. When session state is
enabled for an ASP.NET application, each request for a page in the application is examined for aSessionID value sent from
the browser. If no SessionID value is supplied, ASP.NET starts a new session and the SessionID value for that session is
sent to the browser with the response.
By default, SessionID values are stored in a cookie. However, you can also configure the application to
store SessionID values in the URL for a “cookieless” session.
A session is considered active as long as requests continue to be made with the same SessionID value. If the time between
requests for a particular session exceeds the specified time-out value in minutes, the session is considered expired.
Requests made with an expired SessionIDvalue result in a new session.
Security Note
SessionID values are sent in clear text, whether as a cookie or as part of the URL. A malicious
user could get access to the session of another user by obtaining the SessionID value and
including it in requests to the server. If you are storing sensitive information in session state, it is
recommended that you use SSL to encrypt any communication between the browser and server
that includes the SessionID value.
Cookieless SessionIDs
By default, the SessionID value is stored in a non-expiring session cookie in the browser. However, you can specify that
session identifiers should not be stored in a cookie by setting the cookieless attribute to true in thesessionState section of
the Web.config file.
The following example shows a Web.config file that configures an ASP.NET application to use cookieless session identifiers.
Copy
<configuration>
<system.web>
<sessionState cookieless=”true”
regenerateExpiredSessionId=”true” />
</system.web>
</configuration>
ASP.NET maintains cookieless session state by automatically inserting a unique session ID into the page’s URL. For
example, the following URL has been modified by ASP.NET to include the unique session ID lit3py55t21z5v55vlm25s55:
Copy
http://www.example.com/(S(lit3py55t21z5v55vlm25s55))/orderform.aspx
When ASP.NET sends a page to the browser, it modifies any links in the page that use an application-relative path by
embedding a session ID value in the links. (Links with absolute paths are not modified.) Session state is maintained as
long as the user clicks links that have been modified in this manner. However, if the client rewrites a URL that is supplied
by the application, ASP.NET may not be able to resolve the session ID and associate the request with an existing session.
In that case, a new session is started for the request.
The session ID is embedded in the URL after the slash that follows the application name and before any remaining file or
virtual directory identifier. This enables ASP.NET to resolve the application name before involving theSessionStateModule in
the request.
Note
To improve the security of your application, you should allow users to log out of your
application, at which point the application should call theAbandon method. This reduces the
potential for a malicious user to get the unique identifier in the URL and use it to retrieve private
user data stored in the session.
<FooterTemplate>
<asp:Button ID=”btnAdd” runat=”server” OnClick=”AddRecord” Text=”Add” />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor=”#F7DFB5″ ForeColor=”#8C4510″ />
<PagerStyle ForeColor=”#8C4510″ HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#738A9C” Font-Bold=”True” ForeColor=”White” />
<HeaderStyle BackColor=”#A55129″ Font-Bold=”True” ForeColor=”White” />
</asp:GridView>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader rd;
public _Default()
{
con = new SqlConnection(“initial catalog=abhi;integrated security=yes”);
con.Open();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fill();
}
}
void fill()
{
con.Close();
con.Open();
cmd=new SqlCommand (“select * from Employee”,con);
rd = cmd.ExecuteReader();
GridView1.DataSource = rd;
GridView1.DataBind();
rd.Close();
}
protected void AddRecord(object sender, EventArgs e)
{
TextBox txtEmpId =GridView1.FooterRow.FindControl(“txtEmpId”) as TextBox;
TextBox txtEmpName = GridView1.FooterRow.FindControl(“txtEmpName”) as TextBox;
TextBox txtEmpSalary = GridView1.FooterRow.FindControl(“txtEmpSalary”) as TextBox;
con.Close();
con.Open();
cmd = new SqlCommand(“insert into Employee values(” + Convert.ToInt32(txtEmpId.Text) + “,’” +
txtEmpName.Text + “‘,” + Convert.ToDecimal(txtEmpSalary.Text) + “)”, con);
int t=cmd.ExecuteNonQuery();
if (t>0)
{
fill();
}
}
}
Manipulation(Insert, Update, Delete) in asp.net
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title></title>
<style type=”text/css”>
.style1
{
width: 100%;
}
</style>
</head>
<body>
<form id=”form1″ runat=”server”>
<table class=”style1″>
<tr>
<td>
Emp Id</td>
<td>
<asp:TextBox ID=”txtEmpId” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Emp Name</td>
<td>
<asp:TextBox ID=”txtEmpName” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Emp Salary</td>
<td>
<asp:TextBox ID=”txtEmpSalary” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td colspan=”2″>
<br />
<br />
<asp:Button ID=”btnDisplay” runat=”server” onclick=”btnDisplay_Click”
Text=”Display” />
<asp:Button ID=”btnNext” runat=”server” onclick=”btnNext_Click” Text=”Next” />
<asp:Button ID=”btnPrev” runat=”server” onclick=”btnPrev_Click” Text=”Prev” />
<asp:Button ID=”btnInsert” runat=”server” onclick=”btnInsert_Click”
Text=”Insert” />
<asp:Button ID=”btnUpdate” runat=”server” onclick=”btnUpdate_Click”
Text=”Update” />
<asp:Button ID=”btnDelete” runat=”server” onclick=”btnDelete_Click”
Text=”Delete” />
</td>
</tr>
</table>
<div>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
static int counter;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=abhi;integrated security=yes”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from employee”, con);
adap.Fill(ds, “employee”);
bui = new SqlCommandBuilder(adap);
}
protected void Page_Load(object sender, EventArgs e)
{
}
else
{
}
protected void deleterecord(object sender, GridViewDeleteEventArgs e)
{
adap.DeleteCommand = bui.GetDeleteCommand();
//DataColumn[] dc = new DataColumn[1];
g1.DataSource = ds;
g1.DataBind();
}
protected void editRecord(object sender, GridViewEditEventArgs e)
{
g1.EditIndex = e.NewEditIndex;
fill();
}
protected void cancelRecord(object sender, GridViewCancelEditEventArgs e)
{
g1.EditIndex = -1;
fill();
}
protected void updateRecord(object sender, GridViewUpdateEventArgs e)
{
adap.UpdateCommand = bui.GetUpdateCommand();
Label lblEmpId =g1.Rows[e.RowIndex].FindControl(“lblEmpId”) as Label;
TextBox txtEmpName =g1.Rows[e.RowIndex].FindControl(“txtEmpName”) as TextBox;
TextBox txtEmpSalary = g1.Rows[e.RowIndex].FindControl(“txtEmpSalary”) as TextBox;
DataRow[] dr= ds.Tables["Employee"].Select(“EmpId=”+Convert.ToInt32(lblEmpId.Text)+”");
dr[0]["EmpName"] = txtEmpName.Text;
dr[0]["EmpSalary"] = Convert.ToDecimal(txtEmpSalary.Text);
int temp= adap.Update(ds.Tables["Employee"]);
if (temp>0)
{
g1.EditIndex = -1;
fill();
}
}
record show in Datalist
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:DataList ID=”d1″ runat=”server” RepeatColumns=”3″ >
<ItemTemplate>
<table>
<tr>
<td style=”width:100px;”>
<asp:Label ID=”lblEmpId” runat=”server” Text=’<%# bind(“EmpId”) %>’></asp:Label>
</td></tr>
<tr>
<td style=”width:100px;”><asp:Label ID=”Label1″ runat=”server” Text=’<%# bind(“EmpName”)
%>’></asp:Label></td></tr>
<tr> <td style=”width:100px;”><asp:Label ID=”Label2″ runat=”server” Text=’<%# bind(“EmpSalary”)
%>’></asp:Label></td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
public _Default()
{
con = new SqlConnection(“initial catalog=abhi;integrated security=yes”);
ds = new DataSet();
}
protected void Page_Load(object sender, EventArgs e)
{
fill();
}
void fill()
{
DataList d;
Repeater r1;
adap = new SqlDataAdapter(“select * from Employee”,con);
adap.Fill(ds,”Employee”);
d1.DataSource = ds;
d1.DataBind();
}
}
Difference b/w Repeater,Data List & Grid View :-
Concept Repeater Data List Grid View
Base Class Control Web Control Web Control
Default Output No No Yes
Manipulation No No Yes
Paging No no Yes
Auto Formatting No Yes Yes
Repeat Column No Yes No
Sorting No No Yes
ajax
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title></title>
<script language=”javascript” type=”text/javascript” >
function chk() {
var r = document.getElementById(“TextBox1″).value;
if (r < 60) {
alert(“enter above 60″);
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
</asp:ScriptManager>
<asp:UpdatePanel ID=”up1″ runat=”server”>
<ContentTemplate>
<div>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = System.DateTime.Now.Second.ToString();
TextBox2.Text = System.DateTime.Now.Second.ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(“cac”);
}
protected void btnfirst_Click(object sender, EventArgs e)
{
TextBox1.Text = System.DateTime.Now.Second.ToString();
}
protected void btnsecond_Click(object sender, EventArgs e)
{
TextBox2.Text = System.DateTime.Now.Second.ToString();
}
}
check all in gridview
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!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:GridView ID=”GridView1″ AutoGenerateColumns=”false” runat=”server”>
<Columns>
<asp:TemplateField >
<HeaderTemplate>
<asp:Button ID=”btnDelete” OnClick=”deleterecord” Text=”Delete” runat=”server” />
<asp:CheckBox ID=”chkAll” OnCheckedChanged=”checkallrows” AutoPostBack=”true” runat=”server” />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID=”chkRow” runat=”server” />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Emp Id”>
<ItemTemplate>
<asp:Label ID=”lblEmpId” runat=”server” Text=’<%# bind(“Emp_Id”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Emp Name”>
<ItemTemplate>
<asp:Label ID=”lblEmpName” runat=”server” Text=’<%# bind(“Emp_Name”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Emp Salary”>
<ItemTemplate>
<asp:Label ID=”lblEmpSalary” runat=”server” Text=’<%# bind(“Emp_Salary”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=abhi;integrated security=yes”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from abhinavsir”,con);
adap.Fill(ds,”Emp”);
bui = new SqlCommandBuilder(adap);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fill();
}
}
void fill()
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void checkallrows(object sender, EventArgs e)
{
CheckBox chkall =GridView1.HeaderRow.FindControl(“chkall”) as CheckBox;
}
protected void deleterecord(object sender, EventArgs e)
{
}
}
int t = adap.Update(ds.Tables["Emp"]);
fill();
}
}
Record insert & Delete in gridview though disconnected mode
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!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:GridView OnRowDeleting=”DeleteRecord” AutoGenerateColumns=”False” ShowFooter=”True” ID=”GridView1″
runat=”server”>
<Columns>
<asp:TemplateField>
<HeaderTemplate>Product No</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblProductNo” runat=”server” Text=’<%# bind(“Product_No”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtProductNo” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Product Name</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblProductName” runat=”server” Text=’<%# bind(“Product_Name”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtProductName” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Product Price</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblProductPrice” runat=”server” Text=’<%# bind(“Product_Price”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtProductPrice” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Operation</HeaderTemplate>
<ItemTemplate>
<asp:Button ID=”btnDelete” runat=”server” CommandName=”Delete” Text=”Delete” />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID=”btnSave” runat=”server” OnClick=”saverecord” Text=”Save” />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=ritu;uid=sa;pwd=sa”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from Product”,con);
adap.Fill(ds,”Prod”);
bui = new SqlCommandBuilder(adap);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillrecord();
}
}
void fillrecord()
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void saverecord(object sender, EventArgs e)
{
adap.InsertCommand = bui.GetInsertCommand();
TextBox txtProductNo =GridView1.FooterRow.FindControl(“txtProductNo”) as TextBox;
TextBox txtProductName = GridView1.FooterRow.FindControl(“txtProductName”) as TextBox;
TextBox txtProductPrice = GridView1.FooterRow.FindControl(“txtProductPrice”) as TextBox;
DataRow dr =ds.Tables["Prod"].NewRow();
dr[0] = Convert.ToInt32(txtProductNo.Text);
dr[1] = txtProductName.Text;
dr[2] =Convert.ToDecimal(txtProductPrice.Text);
ds.Tables["Prod"].Rows.Add(dr);
int t=adap.Update(ds.Tables["Prod"]);
if (t>0)
{
fillrecord();
}
}
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
adap.DeleteCommand = bui.GetDeleteCommand();
ds.Tables["Prod"].Rows[e.RowIndex].Delete();
adap.Update(ds.Tables["Prod"]);
fillrecord();
}
}
Record insert & Delete in gridview though disconnected mode
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!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:GridView OnRowDeleting=”DeleteRecord” AutoGenerateColumns=”False” ShowFooter=”True” ID=”GridView1″
runat=”server”>
<Columns>
<asp:TemplateField>
<HeaderTemplate>Product No</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblProductNo” runat=”server” Text=’<%# bind(“Product_No”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtProductNo” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Product Name</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblProductName” runat=”server” Text=’<%# bind(“Product_Name”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtProductName” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Product Price</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblProductPrice” runat=”server” Text=’<%# bind(“Product_Price”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtProductPrice” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Operation</HeaderTemplate>
<ItemTemplate>
<asp:Button ID=”btnDelete” runat=”server” CommandName=”Delete” Text=”Delete” />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID=”btnSave” runat=”server” OnClick=”saverecord” Text=”Save” />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=ritu;uid=sa;pwd=sa”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from Product”,con);
adap.Fill(ds,”Prod”);
bui = new SqlCommandBuilder(adap);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillrecord();
}
}
void fillrecord()
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void saverecord(object sender, EventArgs e)
{
adap.InsertCommand = bui.GetInsertCommand();
TextBox txtProductNo =GridView1.FooterRow.FindControl(“txtProductNo”) as TextBox;
TextBox txtProductName = GridView1.FooterRow.FindControl(“txtProductName”) as TextBox;
TextBox txtProductPrice = GridView1.FooterRow.FindControl(“txtProductPrice”) as TextBox;
DataRow dr =ds.Tables["Prod"].NewRow();
dr[0] = Convert.ToInt32(txtProductNo.Text);
dr[1] = txtProductName.Text;
dr[2] =Convert.ToDecimal(txtProductPrice.Text);
ds.Tables["Prod"].Rows.Add(dr);
int t=adap.Update(ds.Tables["Prod"]);
if (t>0)
{
fillrecord();
}
}
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
adap.DeleteCommand = bui.GetDeleteCommand();
ds.Tables["Prod"].Rows[e.RowIndex].Delete();
adap.Update(ds.Tables["Prod"]);
fillrecord();
}
}
}
protected void editrecord(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
fillrecord();
}
protected void cancelrecord(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
fillrecord();
}
protected void updaterecord(object sender, GridViewUpdateEventArgs e)
{
adap.UpdateCommand = bui.GetUpdateCommand();
Label lblProductNo = GridView1.Rows[e.RowIndex].FindControl(“lblProductNo”) as Label;
TextBox txtProductName = GridView1.Rows[e.RowIndex].FindControl(“txtProductName”) as TextBox;
TextBox txtProductPrice = GridView1.Rows[e.RowIndex].FindControl(“txtProductPrice”) as TextBox;
DataRow[] dr =ds.Tables["Product"].Select(“Product_No=”+Convert.ToInt32(lblProductNo.Text)+”");
dr[0][1] = txtProductName.Text;
dr[0][2] =Convert.ToDecimal(txtProductPrice.Text);
int t =adap.Update(ds,”Product”);
if (t>0)
{
GridView1.EditIndex = -1;
fillrecord();
}
}
}
Check All Through Gridview
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!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:GridView ID=”GridView1″ AutoGenerateColumns=”false” runat=”server”>
<Columns>
<asp:TemplateField >
<HeaderTemplate>
<asp:Button ID=”btnDelete” OnClick=”deleterecord” Text=”Delete” runat=”server” />
<asp:CheckBox Text=”Check All” OnCheckedChanged=”checkRows” AutoPostBack=”true” ID=”chkAll”
runat=”server” />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID=”chkRow” runat=”server” />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Product No”>
<ItemTemplate>
<asp:Label ID=”lblProductNo” runat=”server” Text=’<%# bind(“Product_no”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Product Name”>
<ItemTemplate>
<asp:Label ID=”lblProductName” runat=”server” Text=’<%# bind(“Product_name”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Product Price”>
<ItemTemplate>
<asp:Label ID=”lblProductPrice” runat=”server” Text=’<%# bind(“Product_Price”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=ritu;uid=sa;pwd=sa”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from product”, con);
adap.Fill(ds, “product”);
bui = new SqlCommandBuilder(adap);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillrecord();
}
}
void fillrecord()
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void checkRows(object sender, EventArgs e)
{
CheckBox chkall = GridView1.HeaderRow.FindControl(“chkAll”) as CheckBox;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkrow = GridView1.Rows[i].FindControl(“chkrow”) as CheckBox;
if (chkall.Checked==true)
{
chkrow.Checked = true;
}
else
{
chkrow.Checked = false;
}
}
}
protected void deleterecord(object sender, EventArgs e)
{
adap.DeleteCommand = bui.GetDeleteCommand();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkrow = GridView1.Rows[i].FindControl(“chkrow”) as CheckBox;
if (chkrow.Checked == true)
{
ds.Tables["Product"].Rows[i].Delete();
}
}
int t =adap.Update(ds.Tables["Product"]);
if (t>0)
{
fillrecord();
}
}
}
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Net.Mail;
using
System.Net;
public
partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
MailMessage m = newSystem.Net.Mail.MailMessage(“abhinavdotnet@gmail.com”,“abhsax1@gmail.com”,“aaa”,“asasasas”);
try
{
NetworkCredential n = new NetworkCredential(“username”, “password”);
SmtpClient s = new SmtpClient(“smtp.gmail.com”, 587);
s.EnableSsl = true;
s.UseDefaultCredentials = false;
s.Credentials = n;
s.Send(m);
Response.Write(“m s”);
}
catch (Exception)
{
throw;
}
}
}
Hyperlink in Asp.net
Default.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!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:GridView ID=”g1″ AutoGenerateColumns=”false” runat=”server”>
<Columns>
<asp:HyperLinkField HeaderText=”Emp Id” DataTextField=”EmpId” DataNavigateUrlFields=”EmpId”
DataNavigateUrlFormatString=”detail.aspx?temp={0}” />
<asp:TemplateField HeaderText=”Emp Name”>
<ItemTemplate>
<asp:Label ID=”lblEmpName” runat=”server” Text=’<%# bind(“EmpName”) %>’ ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Emp Salary”>
<ItemTemplate>
<asp:Label ID=”lblEmpSalary” runat=”server” Text=’<%# bind(“EmpSalary”) %>’ ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader rd;
public _Default()
{
con = new SqlConnection(“initial catalog=Employee;integrated security=yes”);
con.Open();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillrecord();
}
}
void fillrecord()
{
cmd = new SqlCommand(“select * from Emp”,con);
rd = cmd.ExecuteReader();
g1.DataSource = rd;
g1.DataBind();
}
}
Detail.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”detail.aspx.cs” Inherits=”detail” %>
<!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:GridView ID=”GridView1″ runat=”server”>
</asp:GridView>
</div>
</form>
</body>
</html>
detail.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class detail : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader rd;
public detail()
{
con = new SqlConnection(“initial catalog=Employee;integrated security=yes”);
con.Open();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillrecord();
}
}
void fillrecord()
{
cmd = new SqlCommand(“select * from Empdetail where
empid=”+Convert.ToInt32(Request.QueryString["temp"].ToString())+”", con);
rd = cmd.ExecuteReader();
GridView1.DataSource = rd;
GridView1.DataBind();
}
}
Server-side options for storing page information typically have higher security than client-side options, but they can use
more Web server resources, which can lead to scalability issues when the size of the information store is large. ASP.NET
provides several options to implement server-side state management. For more information, see ASP.NET State
Management Overview.The following are the server-side state management options that ASP.NET supports:
ASP.NET offers you a variety of ways to maintain state information on the server, rather than persisting information on the
client. With server-based state management, you can decrease the amount of information sent to the client in order to
preserve state, however it can use costly resources on the server. The following sections describe three server-based state
management features: application state, session state, and profile properties.Application StateASP.NET allows you to
save values using application state — which is an instance of the HttpApplicationState class — for each active Web
application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus,
application state is useful for storing information that needs to be maintained between server round trips and between
requests for pages. For more information, see ASP.NET Application State Overview.Application state is stored in a
key/value dictionary that is created during each request to a specific URL. You can add your application-specific
information to this structure to store it between page requests.
Application state is stored in an instance of the HttpApplicationState class. This class exposes a key-value dictionary of
objects.TheHttpApplicationState instance is created the first time a user accesses any URL resource in an application.
The HttpApplicationState class is most often accessed through the Application property of the HttpContext class.You can
use application state in two ways. You can add, access, or remove values from the Contents collection directly through
code. The HttpApplicationStateclass can be accessed at any time during the life of an application. However, it is often
useful to load application state data when the application starts. To do so, you can put code to load application state into
the Application_Start method in the Global.asax file.Alternatively, you can add objects to the StaticObjects collection via an
<object runat=”server”> declaration in your Web application’s Global.asax file. Application state defined in this way can
then be accessed from code anywhere in your application. The following example shows an object declaration for an
application state value:CopyYou can add objects to the StaticObjectscollection only in the Global.asax file. The collection
throws aNotSupportedException if you attempt to add objects directly through code.
1 Response to "Asp.Net"
abhinavdotnetnotes
February 14, 2011 at 5:16 am
I sended fully discription of webservice in c# .net
Reply
Leave a Reply
Top of Form
Your email address will not be published. Required fields are marked *
Name *
Email *
Website
Post Comment
Bottom of Form
• Top Posts
• Latest Comments
• Tags
• Project 2011
• Asp.Net
• Have a nice day
• Ado.Net
• C# .net
• Java Script
• C# Notes
• .Net Framework
Categories
• Uncategorized (1)
Archives
• August 2010
Blog at WordPress.com.
Theme: Albeo by Design Disease.