Caching Data Using Data Source Controls

Data source controls provide data services to data-bound controls such as the GridView, FormView, and DetailsView controls. These services include caching data to help improve the performance of applications in which the data does not change frequently.

To cache data using the SqlDataSource or AccessDataSource controls, you must set the DataSourceMode property of those controls to DataSet. The ObjectDataSource control can cache objects returned by the underlying business object. However, you should not cache objects that hold resources or that maintain state that cannot be shared among multiple requests, such as an open DataReader object.

Caching is not enabled by default for data source controls, but you can enable it by setting the control's EnableCaching property to true. Cached data is refreshed based on the number of seconds you specify using the CacheDuration property.

You can further refine the behavior of a data source control's caching behavior by setting its CacheExpirationPolicy property. Setting the property's value to Absolute forces the cache to be refreshed when the CacheDuration value is exceeded. Setting the CacheExpirationPolicy property to Sliding refreshes the cache only if the CacheDuration value has been exceeded since the last time the cached item was accessed.

Important noteImportant Note:

It is recommended that you set the EnableCaching property to false when client impersonation is enabled and the results from the data source are retrieved based on the client identity. If caching is enabled, cached data for a single user can be viewed by all users and sensitive information could be exposed to an unwanted source. Client impersonation is enabled when the impersonate attribute of the identity configuration element is set to true and anonymous identification is disabled for the application at the Web server.

The following code example shows a SqlDataSource control configured to refresh data every 20 seconds:

<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
    <head runat="server">
    <title>ASP.NET Example</title>
        <form id="form1" runat="server">

                ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
                SelectCommand="SELECT EmployeeID,FirstName,LastName,Title FROM Employees">

                    <asp:BoundField HeaderText="First Name" DataField="FirstName" />
                    <asp:BoundField HeaderText="Last Name" DataField="LastName" />
                    <asp:BoundField HeaderText="Title" DataField="Title" />


If you are using the SqlDataSource control with the System.Data.SqlClient provider, you can take advantage of the SqlCacheDependency class to ensure that cached data is refreshed only when the source table in the database has been modified. For more information, see Caching Data with the SqlDataSource Control.

Community Additions