New Document
Data Sources Controls

ASP.NET includes data source controls that allow you to work with different types of data sources such as a database, an XML file, or a middle-tier business object. Data source controls connect to and retrieve data from a data source and make it available for other controls to bind to, without requiring code. They can also support modifying data.

This topic provides information about the different types of data source controls in ASP.NET. The data source control model is extensible, so you can also create your own data source controls that interact with different data sources or that provide additional functionality for an existing data source.

LinqDataSource Control

The LinqDataSource control enables you to use LINQ in an ASP.NET page to retrieve data from a database table or an in-memory data collection. You can use declarative markup to write all the conditions that are required in order retrieve, filter, order, and group the data. When you retrieve data from a SQL database table, you can also configure a LinqDataSource control to handle update, insert, and delete operations. You can do this writing SQL commands to perform these tasks. By using the LinqDataSource control, you can reduce the amount of code that is required for data operations, compared to performing the same operations in other data source controls.

SqlDataSource Control

The SqlDataSource control retrieves and modifies data using SQL commands. The SqlDataSource control works with Microsoft SQL Server, OLE DB, ODBC, and Oracle databases.

The SqlDataSource control can return results as a DataReader or a DataSet object. It supports sorting, filtering, and caching when the results are returned as a DataSet. When you are working with Microsoft SQL Server, the control has the added benefit that cache results can be invalidated when the database changes, using a SqlCacheDependency object.

EntityDataSource Control

The EntityDataSource control supports data binding scenarios based on the Entity Data Model (EDM). This data specification represents data as sets of entities and relationships. The Entity Framework uses the EDM in object-relational mapping and in other scenarios such as WCF Data Services. The EntityDataSource control supports Entity-SQL (eSQL) as the query language, and it supports the query specification that is exposed by the ObjectQuery class.

ObjectDataSource Control

The ObjectDataSource control works with a business object or other class in Web applications that rely on middle-tier business objects to manage data. The control is designed to interact with an object that implements one or more methods to retrieve or modify data. When data-bound controls interact with the ObjectDataSource control to retrieve or modify data, the ObjectDataSource control passes values from the bound control to the source object as parameters in method calls.

The source object's data-retrieval methods must return a DataSet, DataTable, or DataView object, or an object that implements the IEnumerable interface. If the data is returned as a DataSet, DataTable, or DataView object, the ObjectDataSource control can cache and filter the data. You can also implement advanced paging scenarios if the source object accepts page size and record index information from the ObjectDataSource control.

XmlDataSource Control

The XmlDataSource control reads and writes XML data so that you can work with it using controls such as the TreeView and Menu controls. The XmlDataSource control can read either an XML file or string of XML. If the control is working with an XML file, it can write modified XML back to the source file. If a schema is available that describes the data, the XmlDataSource control can use the schema to expose data using typed members.

You can apply an XSLT transformation to the XML data, which allows you to restructure the raw data from the XML file into a format better suited to the control you want to bind to the XML data.

You can also apply XPath expressions to the XML data, which allows you to filter the XML data to return only certain nodes in the XML tree, to look for nodes that have specific values in them, and so on. Using an XPath expression disables the ability to insert new data.

AccessDataSource Control

The AccessDataSource control is a specialized version of the SqlDataSource control, designed to work specifically with Microsoft Access .mdb files. As with the SqlDataSource control, you use SQL statements to define how the control fetches and retrieves data.

SiteMapDataSource Control

The SiteMapDataSource control works with ASP.NET site maps and provides site navigation data. It is most commonly used with the Menu control. The SiteMapDataSource control is also useful when you want to customize site navigation using site map data with Web server controls that are not specifically designed for navigation, such as the TreeView or DropDownList controls.


A data source control interacts with the data-bound controls and hides the complex data binding processes. These are the tools that provide data to the data bound controls and support execution of operations like insertions, deletions, sorting and updates.

ASP.NET includes data source controls that allow you to work with different types of data sources such as a database, an XML file, or a middle-tier business object. Data source controls connect to and retrieve data from a data source and make it available for other controls to bind to, without requiring code. They can also support modifying data.


This topic provides information about the different types of data source controls in ASP.NET. The data source control model is extensible, so you can also create your own data source controls that interact with different data sources or that provide additional functionality for an existing data source.


Each data source control wraps a particular data provider-relational databases, XML documents or custom classes and helps in:

  • Managing connection.

  • Selection of data

  • Managing presentation aspects like paging, caching etc.

  • Manipulation of data

There are many data source controls available in ASP.Net for accessing data from SQL Server, from ODBC or OLE DB servers, from XML files and from business objects.

Based on type of data, these controls could be divided into two categories: hierarchical data source controls and table-based data source controls.

The data source controls used for hierarchical data are:

  • XMLDataSource-allows binding to XML files and strings with or without schema information

  • SiteMapDataSource-allows binding to a provider that supplies site map information

The data source controls used for tabular data are:

Data source controlsDescription
SqlDataSourcerepresents a connection to an ADO.Net data provider that returns SQL data, including data sources accessible via OLEDB and QDBC
ObjectDataSourceallows binding to a custom .Net business object that returns data
LinqdataSourceallows binding to the results of a Linq-to-SQL query (supported by ASP.Net 3.5 only)
AccessDataSourcerepresents connection to a Microsoft Access database
The Data Source Views

Data source views are objects of the DataSourceView class and represent a customized view of data for different data operations like sorting, filtering etc.

The DataSourceView class serves as the base class for all data source view classes, which define the capabilities of data source controls.

Following table provides the properties of the DataSourceView class:

PropertiesDescription
CanDeleteIndicates whether deletion is allowed on the underlying data source.
CanInsertIndicates whether insertion is allowed on the underlying data source.
CanPage Indicates whether paging is allowed on the underlying data source.
CanRetrieveTotalRowCountIndicates whether total row count information is available.
CanSortIndicates whether the data could be sorted.
CanUpdateIndicates whether updates are allowed on the underlying data source.
Events Gets a list of event-handler delegates for the data source view.
NameName of the view.

Following table provides the methods of the DataSourceView class:

MethodsDescription
CanExecuteDetermines whether the specified command can be executed.
ExecuteCommandExecutes the specific command.
ExecuteDelete Performs a delete operation on the list of data that the DataSourceView object represents.
ExecuteInsertPerforms an insert operation on the list of data that the DataSourceView object represents.
ExecuteSelect Gets a list of data from the underlying data storage.
ExecuteUpdatePerforms an update operation on the list of data that the DataSourceView object represents.
Delete Performs a delete operation on the data associated with the view.
InsertPerforms an insert operation on the data associated with the view.
Select Returns the queried data.
UpdatePerforms an update operation on the data associated with the view.
OnDataSourceViewChangedRaises the DataSourceViewChanged event.
RaiseUnsupportedCapabilitiesErrorCalled by the RaiseUnsupportedCapabilitiesError method to compare the capabilities requested for an ExecuteSelect operation against those that the view supports.
The SqlDataSource Control

The SqlDataSource control represents a connection to a relational database such as SQL Server or Oracle database, or data accessible through OLEDB or Open Database Connectivity (ODBC). Connection to data is made through two important properties ConnectionString and ProviderName.

The following code snippet provides the basic syntax for the control:

<asp:SqlDataSource runat="server" ID="MySqlSource"
ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName  %>'
ConnectionString='<%$ ConnectionStrings:LocalNWind %>'
SelectionCommand= "SELECT * FROM EMPLOYEES" />

<asp:GridView ID="GridView1" runat="server" 
                             DataSourceID="MySqlSource">

Configuring various data operations on the underlying data depends upon the various properties (property groups) of the data source control.

The following table provides the related sets of properties of the SqlDataSource control, which provides the programming interface of the control:

Property GroupDescription
DeleteCommand,
DeleteParameters,
DeleteCommandType
Gets or sets the SQL statement, parameters and type for deleting rows in the underlying data.
FilterExpression,
FilterParameters
Gets or sets the data filtering string and parameters.
InsertCommand,
InsertParameters,
InsertCommandType
Gets or sets the SQL statement, parameters and type for inserting rows in the underlying database.
SelectCommand,
SelectParameters,
SelectCommandType
Gets or sets the SQL statement, parameters and type for retrieving rows from the underlying database.
SortParameterName Gets or sets the name of an input parameter that the command's stored procedure will use to sort data
UpdateCommand,
UpdateParameters,
UpdateCommandType
Gets or sets the SQL statement, parameters and type for updating rows in the underlying data store.

The following code snippet shows a data source control enabled for data manipulation:

<asp:SqlDataSource runat="server" ID= "MySqlSource"
ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName  %>'
ConnectionString=' <%$ ConnectionStrings:LocalNWind %>'
SelectCommand= "SELECT * FROM EMPLOYEES"
UpdateCommand= "UPDATE EMPLOYEES SET LASTNAME=@lame"
DeleteCommand= "DELETE FROM EMPLOYEES WHERE EMPLOYEEID=@eid"
FilterExpression= "EMPLOYEEID > 10">
.....
.....
</asp:SqlDataSource>
The ObjectDataSource Control:

The ObjectDataSource Control enables user-defined classes to associate the output of their methods to data bound controls. The programming interface of this class is almost same as the SqlDataSource control.

Following are two important aspects of binding business objects:

  • The bindable class should have a default constructor, be stateless, and have methods that can be mapped to select, update, insert and delete semantics.

  • The object must update one item at a time, batch operations are not supported.

Let us go directly to an example to work with this control. The student class is our class to be used with an object data source. This class has three properties: a student id, name and city. It has a default constructor and a GetStudents method to be used for retrieving data.

The student class:

public class Student
{
   public int StudentID { get; set; }
   public string Name { get; set; }
   public string City { get; set; }
   public Student()
   { }
   public DataSet GetStudents()
   {
      DataSet ds = new DataSet();
      DataTable dt = new DataTable("Students");
      dt.Columns.Add("StudentID", typeof(System.Int32));
      dt.Columns.Add("StudentName", typeof(System.String));
      dt.Columns.Add("StudentCity", typeof(System.String));
      dt.Rows.Add(new object[] { 1, "M. H. Kabir", "Calcutta" });
      dt.Rows.Add(new object[] { 2, "Ayan J. Sarkar", "Calcutta" });
      ds.Tables.Add(dt);
      return ds;
   }
}

Take the following steps to bind the object with an object data source and retrieve data:

  • Create a new web site. Add a class (Students.cs) to it by right clicking the project from the Solution Explorer, adding a class template and placing the above code in it.

  • Build the solution so that the application can use the reference to the class.

  • Place a object data source control in the web form.

  • Configure the data source by selecting the object.

selecting the object
  • Select a data method(s) for different operations on data. In this example, there is only one method.

Select a data method
  • Place a data bound control like grid view on the page and select the object data source as its underlying data source

Data Bound Control
  • At this stage, the design view should look like the following:

Object Data Source
  • Run the project, it retrieves the hard coded tuples from the students class.

Object Data Result
The AccessDataSource Control:

The AccessDataSource control represents a connection to an Access database. It is based on the SqlDataSource control and provides simpler programming interface. The following code snippet provides the basic syntax for the data source:

<asp:AccessDataSource ID="AccessDataSource1" 
            runat="server" 
            DataFile="~/App_Data/ASPDotNetStepByStep.mdb" 
            SelectCommand="SELECT * FROM [DotNetReferences]">
</asp:AccessDataSource>

The AccessDataSource control opens the database in read-only mode. However, it can also be used for performing insert, update or delete operations. This is done using the ADO.Net commands and parameter collection.

Updates are problematic for Access databases from within an ASP.Net application because an Access database is a plain file and the default account of the ASP.Net application might not have the permission to write to the database file.



Previous                                                                                                                                                    Next